refatoramento fodido para reduzir codigo repetido de rotas
This commit is contained in:
Binary file not shown.
74
back_end/funcs.go
Normal file
74
back_end/funcs.go
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
)
|
||||||
|
|
||||||
|
func jsonError(c echo.Context, code int, msg string) error {
|
||||||
|
return c.JSON(code, resp_json{
|
||||||
|
Status: "Error",
|
||||||
|
Message: msg,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonSuccess(c echo.Context, msg string) error {
|
||||||
|
return c.JSON(http.StatusOK, resp_json{
|
||||||
|
Status: "Success",
|
||||||
|
Message: msg,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func requireSession(c echo.Context) (map[string]string, error) {
|
||||||
|
session, err := ValidSession(c)
|
||||||
|
if err != nil {
|
||||||
|
jsonError(c, http.StatusUnauthorized, err.Error())
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return session, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func anyEmpty(values ...string) bool {
|
||||||
|
for _, v := range values {
|
||||||
|
if strings.TrimSpace(v) == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateField(query string, args ...interface{}) error {
|
||||||
|
_, err := db.Exec(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func readAndValidateImage(file *multipart.FileHeader) (string, error) {
|
||||||
|
if file.Size > 25*1024*1024 {
|
||||||
|
return "", fmt.Errorf("imagem excede 25MB")
|
||||||
|
}
|
||||||
|
ext := strings.ToLower(filepath.Ext(file.Filename))
|
||||||
|
if !formatFILES[ext] {
|
||||||
|
return "", fmt.Errorf("formato inválido")
|
||||||
|
}
|
||||||
|
open, err := file.Open()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer open.Close()
|
||||||
|
data, err := io.ReadAll(open)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.StdEncoding.EncodeToString(data), nil
|
||||||
|
}
|
||||||
@@ -1,55 +1,18 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"path/filepath"
|
|
||||||
"regexp"
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
func logout(c echo.Context) error {
|
|
||||||
_, err := ValidSession(c)
|
|
||||||
if err != nil {
|
|
||||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "para fazer logout você deve estar logado seu cabaço",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
cookie, _ := c.Cookie(cookieName)
|
|
||||||
|
|
||||||
sessionID := cookie.Value
|
|
||||||
delCookie(c, sessionID)
|
|
||||||
|
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
|
||||||
Status: "Success",
|
|
||||||
Message: "Você fez foi deslogado.",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func online(c echo.Context) error {
|
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
|
||||||
Status: "Success",
|
|
||||||
Message: "Api esta online",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func badreq(c echo.Context) error {
|
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "essa rota não foi preparada para requisições do tipo get.",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func registrar(c echo.Context) error {
|
func registrar(c echo.Context) error {
|
||||||
player := c.FormValue("player")
|
player := c.FormValue("player")
|
||||||
password := c.FormValue("password")
|
password := c.FormValue("password")
|
||||||
@@ -57,211 +20,137 @@ func registrar(c echo.Context) error {
|
|||||||
playerlore := c.FormValue("playerlore")
|
playerlore := c.FormValue("playerlore")
|
||||||
|
|
||||||
if !regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(player) {
|
if !regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(player) {
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
return jsonError(c, http.StatusBadRequest, "você usou caracteres proibidos no seu nome")
|
||||||
Status: "Error",
|
|
||||||
Message: "você usou caracteres proibidos no seu nome",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.TrimSpace(player) == "" || strings.TrimSpace(password) == "" || strings.TrimSpace(confpass) == "" || strings.TrimSpace(playerlore) == "" {
|
if anyEmpty(player, password, confpass, playerlore) {
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
return jsonError(c, http.StatusBadRequest, "algum parametro esta faltando ou esta vazio, tente novamente")
|
||||||
Status: "Error",
|
|
||||||
Message: "algum parametro esta faltando ou esta vazio, tente novamente",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if password != confpass {
|
if password != confpass {
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
return jsonError(c, http.StatusBadRequest, "Suas senhas não são iguais, verifique e tente novamente.")
|
||||||
Status: "Error",
|
|
||||||
Message: "Suas senhas não são iguais, verifique e tente novamente.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
passhash, err := bcrypt.GenerateFromPassword([]byte(password), 15)
|
passhash, err := bcrypt.GenerateFromPassword([]byte(password), 15)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Algo deu errado com a hash de senha.")
|
log.Println("Algo deu errado com a hash de senha.")
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
return jsonError(c, http.StatusInternalServerError, "Erro ao criar hash de senha do usuario: "+player)
|
||||||
Status: "Error",
|
|
||||||
Message: "Erro ao criar hash de senha do usuario: " + player,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
format := formatFILES
|
imageFile, err := c.FormFile("PlayerImage")
|
||||||
|
|
||||||
ImageFile, err := c.FormFile("PlayerImage")
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
return jsonError(c, http.StatusBadRequest, "Arquivo de Imagem não foi enviado, adcione uma imagem.")
|
||||||
Status: "Error",
|
|
||||||
Message: "Arquivo de Imagem não foi enviado, adcione uma imagem.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if !format[strings.ToLower(filepath.Ext(ImageFile.Filename))] {
|
encode, err := readAndValidateImage(imageFile)
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "sua imagem deve ser png, jpg, jpeg ou gif.",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
openfile, err := ImageFile.Open()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
return jsonError(c, http.StatusBadRequest, err.Error())
|
||||||
Status: "Error",
|
|
||||||
Message: "não foi possivel ler sua imagem",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
defer openfile.Close()
|
|
||||||
if ImageFile.Size > 25*1024*1024 {
|
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "Sua imagem deve ter no maximo 25MB",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
readFile, err := io.ReadAll(openfile)
|
|
||||||
if err != nil {
|
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "não foi possivel ler sua Imagem, tente novamente.",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
encode := base64.StdEncoding.EncodeToString(readFile)
|
|
||||||
var id int
|
var id int
|
||||||
err = db.QueryRow("SELECT id FROM players WHERE player=? LIMIT 1", player).Scan(&id)
|
err = db.QueryRow("SELECT id FROM players WHERE player=? LIMIT 1", player).Scan(&id)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
log.Println(id)
|
return jsonError(c, http.StatusConflict, "Esse usuario ja esta em uso, escolha outro e tente novamente.")
|
||||||
return c.JSON(http.StatusConflict, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "Esse usuario ja esta em uso, escolha outro e tente novamente.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
row, err := db.Exec("INSERT INTO players (foto, player, password, nome, descrição) VALUES (?, ?, ?, ?, ?);", encode, player, string(passhash), "John Doe", playerlore)
|
row, err := db.Exec("INSERT INTO players (foto, player, password, nome, descrição) VALUES (?, ?, ?, ?, ?);", encode, player, string(passhash), "John Doe", playerlore)
|
||||||
if err == nil {
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
return jsonError(c, http.StatusInternalServerError, "Erro ao criar sua conta, tente novamente")
|
||||||
|
}
|
||||||
|
|
||||||
newID, _ := row.LastInsertId()
|
newID, _ := row.LastInsertId()
|
||||||
|
|
||||||
query := fmt.Sprintf("CREATE TABLE invPower_%s (id INT NOT NULL AUTO_INCREMENT, name_power VARCHAR(30) NOT NULL, desc_power LONGTEXT NOT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB;", player)
|
query := fmt.Sprintf("CREATE TABLE invPower_%s (id INT NOT NULL AUTO_INCREMENT, name_power VARCHAR(30) NOT NULL, desc_power LONGTEXT NOT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB;", player)
|
||||||
_, err := db.Exec(query)
|
_, err = db.Exec(query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
db.Exec("DELETE FROM players WHERE id=?", int(newID))
|
db.Exec("DELETE FROM players WHERE id=?", int(newID))
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
return jsonError(c, http.StatusInternalServerError, "erro ao criar inventario de poderes do player: "+player)
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao criar o inventario de poderes do player: " + player,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
log.Printf("tabela invPower_%s foi criada.\n", player)
|
|
||||||
|
|
||||||
query = fmt.Sprintf(`CREATE TABLE inv_%s (id INT NOT NULL AUTO_INCREMENT, item_nome VARCHAR(30) NOT NULL , quantidade INT NOT NULL DEFAULT '1' , item_peso INT NOT NULL DEFAULT '1' , item_durabilit BOOLEAN NOT NULL DEFAULT FALSE ) ENGINE = InnoDB;`, player)
|
query = fmt.Sprintf(`CREATE TABLE inv_%s (id INT NOT NULL AUTO_INCREMENT, item_nome VARCHAR(30) NOT NULL , quantidade INT NOT NULL DEFAULT '1' , item_peso INT NOT NULL DEFAULT '1' , item_durabilit BOOLEAN NOT NULL DEFAULT FALSE ) ENGINE = InnoDB;`, player)
|
||||||
newInv, err := db.Query(query)
|
newInv, err := db.Query(query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
return jsonError(c, http.StatusInternalServerError, "erro ao criar o inventario do player: "+player)
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao criar o inventario do player: " + player,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
newInv.Next()
|
newInv.Next()
|
||||||
defer newInv.Close()
|
defer newInv.Close()
|
||||||
log.Printf("tabela inv_%s foi criada.\n", player)
|
|
||||||
|
|
||||||
newCookie, err := sessionCookie(int(newID), player)
|
newCookie, err := sessionCookie(int(newID), player)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
return jsonError(c, http.StatusInternalServerError, err.Error())
|
||||||
Status: "Error",
|
|
||||||
Message: err.Error(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
c.SetCookie(newCookie)
|
c.SetCookie(newCookie)
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
|
||||||
Status: "Success",
|
return jsonSuccess(c, "sua conta foi criada com sucesso")
|
||||||
Message: "sua conta foi criada com sucesso",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
log.Println(err)
|
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "Erro ao criar sua conta, tente novamente",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func login(c echo.Context) error {
|
func login(c echo.Context) error {
|
||||||
player := c.FormValue("player")
|
player := c.FormValue("player")
|
||||||
password := c.FormValue("password")
|
password := c.FormValue("password")
|
||||||
|
|
||||||
if strings.TrimSpace(player) == "" || strings.TrimSpace(password) == "" {
|
if anyEmpty(player, password) {
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
return jsonError(c, http.StatusBadRequest, "algum parametro está faltando ou está vazio, tente novamente")
|
||||||
Status: "Error",
|
|
||||||
Message: "algum parametro esta faltando ou esta vaziu, tente novamente",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var id int
|
var id int
|
||||||
var DBpass string
|
var DBpass string
|
||||||
err := db.QueryRow("SELECT id, password FROM players WHERE player=? LIMIT 1", player).Scan(&id, &DBpass)
|
err := db.QueryRow("SELECT id, password FROM players WHERE player=? LIMIT 1", player).Scan(&id, &DBpass)
|
||||||
|
if err == nil && bcrypt.CompareHashAndPassword([]byte(DBpass), []byte(password)) == nil {
|
||||||
if err == nil {
|
|
||||||
if bcrypt.CompareHashAndPassword([]byte(DBpass), []byte(password)) == nil {
|
|
||||||
newCookie, err := sessionCookie(id, player)
|
newCookie, err := sessionCookie(id, player)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
|
return jsonError(c, http.StatusInternalServerError, err.Error())
|
||||||
}
|
}
|
||||||
c.SetCookie(newCookie)
|
c.SetCookie(newCookie)
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
return jsonSuccess(c, "Login sucesso")
|
||||||
Status: "Success",
|
|
||||||
Message: "Login sucesso",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
return jsonError(c, http.StatusUnauthorized, "Usuario ou senha incorreto")
|
||||||
Status: "Error",
|
}
|
||||||
Message: "Usuario ou senha incorreto",
|
|
||||||
})
|
func logout(c echo.Context) error {
|
||||||
|
_, err := requireSession(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
cookie, _ := c.Cookie(cookieName)
|
||||||
|
sessionID := cookie.Value
|
||||||
|
delCookie(c, sessionID)
|
||||||
|
return jsonSuccess(c, "Você fez foi deslogado.")
|
||||||
|
}
|
||||||
|
|
||||||
|
func online(c echo.Context) error {
|
||||||
|
return jsonSuccess(c, "Api esta online")
|
||||||
|
}
|
||||||
|
|
||||||
|
func badreq(c echo.Context) error {
|
||||||
|
return jsonError(c, http.StatusBadRequest, "essa rota não foi preparada para requisições do tipo get.")
|
||||||
}
|
}
|
||||||
|
|
||||||
func roll(c echo.Context) error {
|
func roll(c echo.Context) error {
|
||||||
userSession, err := ValidSession(c)
|
session, err := requireSession(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
return nil
|
||||||
Status: "Error",
|
|
||||||
Message: err.Error(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
roll, err := strconv.Atoi(c.FormValue("roll"))
|
roll, err := strconv.Atoi(c.FormValue("roll"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
return jsonError(c, http.StatusBadRequest, "algo deu errado ao rolar seu dado, tente novamente")
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao rola seu dado, tente novamente",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
var dado int
|
|
||||||
switch roll {
|
allowed := map[int]bool{6: true, 10: true, 20: true, 40: true, 50: true, 100: true}
|
||||||
case 6:
|
if !allowed[roll] {
|
||||||
dado = rand.Intn(roll) + 1
|
return jsonError(c, http.StatusBadRequest, "você só pode rodar dados de 6, 10, 20, 40, 50 ou 100")
|
||||||
case 10:
|
|
||||||
dado = rand.Intn(roll) + 1
|
|
||||||
case 20:
|
|
||||||
dado = rand.Intn(roll) + 1
|
|
||||||
case 40:
|
|
||||||
dado = rand.Intn(roll) + 1
|
|
||||||
case 50:
|
|
||||||
dado = rand.Intn(roll) + 1
|
|
||||||
case 100:
|
|
||||||
dado = rand.Intn(roll) + 1
|
|
||||||
default:
|
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "você so pode rodar dados de 6, 10, 20, 40, 50 ou 100",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
var value string = fmt.Sprintf("%s rolou 1d%v e o resultado é %v", userSession["playerName"], roll, dado)
|
|
||||||
|
dado := rand.Intn(roll) + 1
|
||||||
|
value := fmt.Sprintf("%s rolou 1d%v e o resultado é %v", session["playerName"], roll, dado)
|
||||||
|
|
||||||
_, err = db.Exec("INSERT INTO roll_logs (id, log) VALUES (NULL, ?);", value)
|
_, err = db.Exec("INSERT INTO roll_logs (id, log) VALUES (NULL, ?);", value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
return jsonError(c, http.StatusInternalServerError, "não foi possível inserir o log da rolagem no banco de dados")
|
||||||
Status: "Error",
|
|
||||||
Message: "não foi possivel inserir o log do da rolagem no banco de dados",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
return c.JSON(http.StatusOK, resp_json{
|
||||||
Status: "Success",
|
Status: "Success",
|
||||||
@@ -273,21 +162,16 @@ func roll_get(c echo.Context) error {
|
|||||||
row, err := db.Query("SELECT * FROM roll_logs ORDER BY id DESC LIMIT 5;")
|
row, err := db.Query("SELECT * FROM roll_logs ORDER BY id DESC LIMIT 5;")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Erro ao consultar tabela de rolagem.")
|
log.Println("Erro ao consultar tabela de rolagem.")
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao consultar tabela de rolagem")
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao consultar tabela de rolagem",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
var lista []logEntry
|
defer row.Close()
|
||||||
|
|
||||||
|
var lista []logEntry
|
||||||
for row.Next() {
|
for row.Next() {
|
||||||
var id int
|
var id int
|
||||||
var log string
|
var log string
|
||||||
if err := row.Scan(&id, &log); err != nil {
|
if err := row.Scan(&id, &log); err != nil {
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao montar lista de rolagem")
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao montar lista de rolagem",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
lista = append(lista, logEntry{ID: id, Log: log})
|
lista = append(lista, logEntry{ID: id, Log: log})
|
||||||
}
|
}
|
||||||
@@ -296,12 +180,10 @@ func roll_get(c echo.Context) error {
|
|||||||
return lista[i].ID < lista[j].ID
|
return lista[i].ID < lista[j].ID
|
||||||
})
|
})
|
||||||
|
|
||||||
if len(lista) <= 0 {
|
if len(lista) == 0 {
|
||||||
return c.JSON(http.StatusNotFound, resp_json{
|
return jsonError(c, http.StatusNotFound, "Ainda não existe histórico de rolagem")
|
||||||
Status: "NoDB",
|
|
||||||
Message: "Ainda não exite historico de rolagem",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
return c.JSON(http.StatusOK, resp_json{
|
||||||
Status: "Success",
|
Status: "Success",
|
||||||
Logs: lista,
|
Logs: lista,
|
||||||
@@ -309,114 +191,94 @@ func roll_get(c echo.Context) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func player_data(c echo.Context) error {
|
func player_data(c echo.Context) error {
|
||||||
userSession, err := ValidSession(c)
|
session, err := requireSession(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
return nil
|
||||||
Status: "Error",
|
|
||||||
Message: err.Error(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
var foto, playername, vida, descrição string
|
|
||||||
var conhecimento, level, idade, vd, vdm, destresa, inteligencia, força, constituição, cárisma, inventario int64
|
var foto, nome, vida, descricao string
|
||||||
|
var conhecimento, level, idade, vd, vdm, destreza, inteligencia, forca, constituicao, carisma, inventario int64
|
||||||
var altura float64
|
var altura float64
|
||||||
err = db.QueryRow("SELECT foto, nome, conhecimento, level, idade, altura, vida, vida_maxima, destresa, inteligencia, força, constituição, cárisma, inventario, descrição FROM players WHERE id=? LIMIT 1;", userSession["user_id"]).Scan(&foto, &playername, &conhecimento, &level, &idade, &altura, &vd, &vdm, &destresa, &inteligencia, &força, &constituição, &cárisma, &inventario, &descrição)
|
|
||||||
if err == nil {
|
err = db.QueryRow(`SELECT foto, nome, conhecimento, level, idade, altura, vida, vida_maxima,
|
||||||
|
destresa, inteligencia, força, constituição, cárisma, inventario, descrição
|
||||||
|
FROM players WHERE id=? LIMIT 1;`, session["user_id"]).
|
||||||
|
Scan(&foto, &nome, &conhecimento, &level, &idade, &altura, &vd, &vdm,
|
||||||
|
&destreza, &inteligencia, &forca, &constituicao, &carisma, &inventario, &descricao)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return jsonError(c, http.StatusBadRequest, "Algo deu errado ao carregar dados da sua ficha")
|
||||||
|
}
|
||||||
|
|
||||||
vida = fmt.Sprintf("%v/%v", vd, vdm)
|
vida = fmt.Sprintf("%v/%v", vd, vdm)
|
||||||
porcentagem := (float64(vd) / float64(vdm)) * 100
|
porcentagem := (float64(vd) / float64(vdm)) * 100
|
||||||
|
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
return c.JSON(http.StatusOK, resp_json{
|
||||||
Status: "Success",
|
Status: "Success",
|
||||||
Foto: foto,
|
Foto: foto,
|
||||||
PlayerName: playername,
|
PlayerName: nome,
|
||||||
Conhecimento: &conhecimento,
|
Conhecimento: &conhecimento,
|
||||||
Level: &level,
|
Level: &level,
|
||||||
Idade: &idade,
|
Idade: &idade,
|
||||||
Altura: &altura,
|
Altura: &altura,
|
||||||
Vida: vida,
|
Vida: vida,
|
||||||
VidaPorcentagem: &porcentagem,
|
VidaPorcentagem: &porcentagem,
|
||||||
Destresa: &destresa,
|
Destresa: &destreza,
|
||||||
Inteligencia: &inteligencia,
|
Inteligencia: &inteligencia,
|
||||||
Força: &força,
|
Força: &forca,
|
||||||
Constituição: &constituição,
|
Constituição: &constituicao,
|
||||||
Cárisma: &cárisma,
|
Cárisma: &carisma,
|
||||||
Inventario: &inventario,
|
Inventario: &inventario,
|
||||||
Descrição: descrição,
|
Descrição: descricao,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "Algo deu errado ao carregar dados da sua ficha",
|
|
||||||
})
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func player_update(c echo.Context) error {
|
func player_update(c echo.Context) error {
|
||||||
userSession, err := ValidSession(c)
|
session, err := requireSession(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
return nil
|
||||||
Status: "Error",
|
|
||||||
Message: err.Error(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
updown := c.Param("updown")
|
updown := c.Param("updown")
|
||||||
atb := c.Param("atb")
|
atb := c.Param("atb")
|
||||||
var sinal string
|
|
||||||
|
|
||||||
switch updown {
|
sinal := map[string]string{"up": "+", "down": "-"}[updown]
|
||||||
case "up":
|
if sinal == "" {
|
||||||
sinal = "+"
|
return jsonError(c, http.StatusBadRequest, "você passou um parametro invalido em updown, use up ou down.")
|
||||||
case "down":
|
|
||||||
sinal = "-"
|
|
||||||
default:
|
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "você passou um parametro invalido em updown, use up ou down.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var updateList = map[string]string{
|
updateList := map[string]string{
|
||||||
"vida": fmt.Sprintf("UPDATE players SET vida = vida %s 1 WHERE id=?;", sinal),
|
"vida": "vida",
|
||||||
"level": fmt.Sprintf("UPDATE players SET level = level %s 1 WHERE id=?;", sinal),
|
"level": "level",
|
||||||
"idade": fmt.Sprintf("UPDATE players SET idade = idade %s 1 WHERE id=?;", sinal),
|
"idade": "idade",
|
||||||
"conhecimento": fmt.Sprintf("UPDATE players SET conhecimento = conhecimento %s 1 WHERE id=?;", sinal),
|
"conhecimento": "conhecimento",
|
||||||
"força": fmt.Sprintf("UPDATE players SET força = força %s 1 WHERE id=?;", sinal),
|
"força": "força",
|
||||||
"destresa": fmt.Sprintf("UPDATE players SET destresa = destresa %s 1 WHERE id=?;", sinal),
|
"destresa": "destresa",
|
||||||
"constituição": fmt.Sprintf("UPDATE players SET constituição = constituição %s 1 WHERE id=?;", sinal),
|
"constituição": "constituição",
|
||||||
"inteligencia": fmt.Sprintf("UPDATE players SET inteligencia = inteligencia %s 1 WHERE id=?;", sinal),
|
"inteligencia": "inteligencia",
|
||||||
"cárisma": fmt.Sprintf("UPDATE players SET cárisma = cárisma %s 1 WHERE id=?;", sinal),
|
"cárisma": "cárisma",
|
||||||
}
|
}
|
||||||
|
|
||||||
query, ok := updateList[atb]
|
field, ok := updateList[atb]
|
||||||
if !ok {
|
if !ok {
|
||||||
return c.JSON(http.StatusBadRequest, resp_json{
|
return jsonError(c, http.StatusBadRequest, "você passou um parametro invalido, tente novamente com um parametro correto")
|
||||||
Status: "Error",
|
|
||||||
Message: "você passou um parametro invalido, tente novamente com um parametro correto",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
_, err = db.Exec(query, userSession["user_id"])
|
|
||||||
if err != nil {
|
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado a atualizar sua ficha",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
query := fmt.Sprintf("UPDATE players SET %s = %s %s 1 WHERE id=?;", field, field, sinal)
|
||||||
Status: "Success",
|
if err := updateField(query, session["user_id"]); err != nil {
|
||||||
Message: sinal + "1 em " + atb,
|
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao atualizar sua ficha")
|
||||||
})
|
}
|
||||||
|
|
||||||
|
return jsonSuccess(c, sinal+"1 em "+atb)
|
||||||
}
|
}
|
||||||
|
|
||||||
func player_updateInputs(c echo.Context) error {
|
func player_updateInputs(c echo.Context) error {
|
||||||
userSession, err := ValidSession(c)
|
session, err := requireSession(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
return nil
|
||||||
Status: "Error",
|
|
||||||
Message: err.Error(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var lista []string
|
var lista []string
|
||||||
|
|
||||||
vida := c.FormValue("vida")
|
vida := c.FormValue("vida")
|
||||||
nome := c.FormValue("nome")
|
nome := c.FormValue("nome")
|
||||||
altura := c.FormValue("altura")
|
altura := c.FormValue("altura")
|
||||||
@@ -424,156 +286,99 @@ func player_updateInputs(c echo.Context) error {
|
|||||||
lore := c.FormValue("lore")
|
lore := c.FormValue("lore")
|
||||||
|
|
||||||
if vida != "" {
|
if vida != "" {
|
||||||
_, err = db.Exec("UPDATE players SET vida=?, vida_maxima=? WHERE id=?;", vida, vida, userSession["user_id"])
|
err := updateField("UPDATE players SET vida=?, vida_maxima=? WHERE id=?;", vida, vida, session["user_id"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar sua vida.")
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao alterar sua vida.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
lista = append(lista, "vida")
|
lista = append(lista, "vida")
|
||||||
}
|
}
|
||||||
|
|
||||||
if nome != "" {
|
if nome != "" {
|
||||||
_, err = db.Exec("UPDATE players SET nome=? WHERE id=?;", nome, userSession["user_id"])
|
err := updateField("UPDATE players SET nome=? WHERE id=?;", nome, session["user_id"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar seu nome.")
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao alterar seu nome.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
lista = append(lista, "nome")
|
lista = append(lista, "nome")
|
||||||
}
|
}
|
||||||
|
|
||||||
if altura != "" {
|
if altura != "" {
|
||||||
_, err = db.Exec("UPDATE players SET altura=? WHERE id=?;", altura, userSession["user_id"])
|
err := updateField("UPDATE players SET altura=? WHERE id=?;", altura, session["user_id"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar sua altura.")
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao alterar sua altura.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
lista = append(lista, "altura")
|
lista = append(lista, "altura")
|
||||||
}
|
}
|
||||||
|
|
||||||
if inv != "" {
|
if inv != "" {
|
||||||
row, err := db.Query(fmt.Sprintf("SELECT id, item_peso FROM inv_%s ORDER BY id DESC;", userSession["playerName"]))
|
row, err := db.Query(fmt.Sprintf("SELECT item_peso FROM inv_%s;", session["playerName"]))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
return jsonError(c, http.StatusInternalServerError, "Erro ao consultar itens do inventário.")
|
||||||
log.Println("Erro ao consultar items do inventario.")
|
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "Erro ao consultar items do inventario.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
var peso_total int = 0
|
defer row.Close()
|
||||||
|
var total int
|
||||||
for row.Next() {
|
for row.Next() {
|
||||||
var id int
|
|
||||||
var peso int
|
var peso int
|
||||||
if err := row.Scan(&id, &peso); err != nil {
|
if err := row.Scan(&peso); err != nil {
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
return jsonError(c, http.StatusInternalServerError, "Erro ao ler itens do inventário")
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao inventario",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
peso_total = peso_total + peso
|
total += peso
|
||||||
}
|
}
|
||||||
valorInv, _ := strconv.Atoi(inv)
|
val, _ := strconv.Atoi(inv)
|
||||||
if peso_total > valorInv {
|
if total > val {
|
||||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
return jsonError(c, http.StatusUnauthorized, "você não pode ter um inventário com menos capacidade do que está carregando")
|
||||||
Status: "Error",
|
|
||||||
Message: "você não pode ter um inventario com menos capacidade do que esta carregando.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
err = updateField("UPDATE players SET inventario=? WHERE id=?;", inv, session["user_id"])
|
||||||
_, err = db.Exec("UPDATE players SET inventario=? WHERE id=?;", inv, userSession["user_id"])
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar tamanho do inventário")
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao alterar o tamanho do seu inventario.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
lista = append(lista, "inventario")
|
lista = append(lista, "inventario")
|
||||||
}
|
}
|
||||||
|
|
||||||
if lore != "" {
|
if lore != "" {
|
||||||
_, err = db.Exec("UPDATE players SET descrição=? WHERE id=?;", lore, userSession["user_id"])
|
err := updateField("UPDATE players SET descrição=? WHERE id=?;", lore, session["user_id"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar a sua história")
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao alterar a sua historia.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
lista = append(lista, "lore")
|
lista = append(lista, "lore")
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(lista) <= 0 {
|
if len(lista) == 0 {
|
||||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
return jsonError(c, http.StatusUnauthorized, "você é obrigado a alterar alguma informação")
|
||||||
Status: "Error",
|
|
||||||
Message: "você é obrigado a alguma informação seu cabaço.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
|
||||||
Status: "Success",
|
return jsonSuccess(c, fmt.Sprintf("você mudou as seguintes informações: %s", lista))
|
||||||
Message: fmt.Sprintf("você mudou as seguintes informaçôes: %s", lista),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func inv_get(c echo.Context) error {
|
func inv_get(c echo.Context) error {
|
||||||
userSession, err := ValidSession(c)
|
session, err := requireSession(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
return nil
|
||||||
Status: "Error",
|
|
||||||
Message: err.Error(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
row, err := db.Query(fmt.Sprintf("SELECT id, item_nome, quantidade, item_peso FROM inv_%s ORDER BY id DESC;", userSession["playerName"]))
|
row, err := db.Query(fmt.Sprintf("SELECT id, item_nome, quantidade, item_peso FROM inv_%s ORDER BY id DESC;", session["playerName"]))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
return jsonError(c, http.StatusInternalServerError, "Erro ao consultar itens do inventário.")
|
||||||
log.Println("Erro ao consultar items do inventario.")
|
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "Erro ao consultar items do inventario.",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
var peso_total int = 0
|
defer row.Close()
|
||||||
|
|
||||||
|
var total int
|
||||||
var lista []plyInv
|
var lista []plyInv
|
||||||
|
|
||||||
for row.Next() {
|
for row.Next() {
|
||||||
var id int
|
var item plyInv
|
||||||
var nome string
|
if err := row.Scan(&item.ID, &item.ItemName, &item.ItemQuantidade, &item.ItemPeso); err != nil {
|
||||||
var quantidade int
|
return jsonError(c, http.StatusInternalServerError, "Erro ao ler item do inventário")
|
||||||
var peso int
|
|
||||||
if err := row.Scan(&id, &nome, &quantidade, &peso); err != nil {
|
|
||||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
||||||
Status: "Error",
|
|
||||||
Message: "algo deu errado ao inventario",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
lista = append(lista, plyInv{ID: id, ItemName: nome, ItemQuantidade: quantidade, ItemPeso: peso})
|
lista = append(lista, item)
|
||||||
peso_total = peso_total + peso
|
total += item.ItemPeso
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Slice(lista, func(i, j int) bool {
|
sort.Slice(lista, func(i, j int) bool {
|
||||||
return lista[i].ID < lista[j].ID
|
return lista[i].ID < lista[j].ID
|
||||||
})
|
})
|
||||||
|
|
||||||
if len(lista) <= 0 {
|
if len(lista) == 0 {
|
||||||
return c.JSON(http.StatusNotFound, resp_json{
|
return jsonError(c, http.StatusNotFound, "O inventário ainda está vazio")
|
||||||
Status: "NoDB",
|
|
||||||
Message: "o Inventario ainda esta vazio",
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.JSON(http.StatusOK, resp_json{
|
return c.JSON(http.StatusOK, resp_json{
|
||||||
Status: "Success",
|
Status: "Success",
|
||||||
InvPeso: peso_total,
|
InvPeso: total,
|
||||||
InvItems: lista,
|
InvItems: lista,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user