482 lines
14 KiB
Go
482 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"math/rand"
|
|
"net/http"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"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 {
|
|
player := c.FormValue("player")
|
|
password := c.FormValue("password")
|
|
confpass := c.FormValue("confirmpassword")
|
|
playerlore := c.FormValue("playerlore")
|
|
|
|
if !regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(player) {
|
|
return c.JSON(http.StatusBadRequest, resp_json{
|
|
Status: "Error",
|
|
Message: "você usou caracteres proibidos no seu nome",
|
|
})
|
|
}
|
|
|
|
if strings.TrimSpace(player) == "" || strings.TrimSpace(password) == "" || strings.TrimSpace(confpass) == "" || strings.TrimSpace(playerlore) == "" {
|
|
return c.JSON(http.StatusBadRequest, resp_json{
|
|
Status: "Error",
|
|
Message: "algum parametro esta faltando ou esta vazio, tente novamente",
|
|
})
|
|
}
|
|
|
|
if password != confpass {
|
|
return c.JSON(http.StatusBadRequest, resp_json{
|
|
Status: "Error",
|
|
Message: "Suas senhas não são iguais, verifique e 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,
|
|
})
|
|
}
|
|
|
|
format := formatFILES
|
|
|
|
ImageFile, err := c.FormFile("PlayerImage")
|
|
if err != nil {
|
|
return c.JSON(http.StatusBadRequest, resp_json{
|
|
Status: "Error",
|
|
Message: "Arquivo de Imagem não foi enviado, adcione uma imagem.",
|
|
})
|
|
}
|
|
|
|
if !format[strings.ToLower(filepath.Ext(ImageFile.Filename))] {
|
|
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 {
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
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
|
|
err = db.QueryRow("SELECT id FROM players WHERE player=? LIMIT 1", player).Scan(&id)
|
|
if err == nil {
|
|
log.Println(id)
|
|
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)
|
|
if err == nil {
|
|
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)
|
|
_, err := db.Exec(query)
|
|
if err != nil {
|
|
db.Exec("DELETE FROM players WHERE id=?", int(newID))
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
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 , 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)
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
Status: "Error",
|
|
Message: "algo deu errado ao criar o inventario do player: " + player,
|
|
})
|
|
}
|
|
newInv.Next()
|
|
defer newInv.Close()
|
|
log.Printf("tabela inv_%s foi criada.\n", player)
|
|
|
|
newCookie, err := sessionCookie(int(newID), player)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
Status: "Error",
|
|
Message: err.Error(),
|
|
})
|
|
}
|
|
c.SetCookie(newCookie)
|
|
return c.JSON(http.StatusOK, resp_json{
|
|
Status: "Success",
|
|
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 {
|
|
player := c.FormValue("player")
|
|
password := c.FormValue("password")
|
|
|
|
if strings.TrimSpace(player) == "" || strings.TrimSpace(password) == "" {
|
|
return c.JSON(http.StatusBadRequest, resp_json{
|
|
Status: "Error",
|
|
Message: "algum parametro esta faltando ou esta vaziu, tente novamente",
|
|
})
|
|
}
|
|
|
|
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, player)
|
|
|
|
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.StatusUnauthorized, resp_json{
|
|
Status: "Error",
|
|
Message: "Usuario ou senha incorreto",
|
|
})
|
|
}
|
|
|
|
func roll(c echo.Context) error {
|
|
userSession, err := ValidSession(c)
|
|
if err != nil {
|
|
return c.JSON(http.StatusUnauthorized, resp_json{
|
|
Status: "Error",
|
|
Message: err.Error(),
|
|
})
|
|
}
|
|
roll, err := strconv.Atoi(c.FormValue("roll"))
|
|
if err != nil {
|
|
return c.JSON(http.StatusBadRequest, resp_json{
|
|
Status: "Error",
|
|
Message: "algo deu errado ao rola seu dado, tente novamente",
|
|
})
|
|
}
|
|
var dado int
|
|
switch roll {
|
|
case 6:
|
|
dado = rand.Intn(roll) + 1
|
|
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)
|
|
|
|
_, err = db.Exec("INSERT INTO roll_logs (id, log) VALUES (NULL, ?);", value)
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
Status: "Error",
|
|
Message: "não foi possivel inserir o log do da rolagem no banco de dados",
|
|
})
|
|
}
|
|
return c.JSON(http.StatusOK, resp_json{
|
|
Status: "Success",
|
|
Message: value,
|
|
})
|
|
}
|
|
|
|
func roll_get(c echo.Context) error {
|
|
row, err := db.Query("SELECT * FROM roll_logs ORDER BY id DESC LIMIT 5;")
|
|
if err != nil {
|
|
log.Println("Erro ao consultar tabela de rolagem.")
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
Status: "Error",
|
|
Message: "algo deu errado ao consultar tabela de rolagem",
|
|
})
|
|
}
|
|
var lista []logEntry
|
|
|
|
for row.Next() {
|
|
var id int
|
|
var log string
|
|
if err := row.Scan(&id, &log); err != nil {
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
Status: "Error",
|
|
Message: "algo deu errado ao montar lista de rolagem",
|
|
})
|
|
}
|
|
lista = append(lista, logEntry{ID: id, Log: log})
|
|
}
|
|
|
|
sort.Slice(lista, func(i, j int) bool {
|
|
return lista[i].ID < lista[j].ID
|
|
})
|
|
|
|
if len(lista) <= 0 {
|
|
return c.JSON(http.StatusNotFound, resp_json{
|
|
Status: "NoDB",
|
|
Message: "Ainda não exite historico de rolagem",
|
|
})
|
|
}
|
|
return c.JSON(http.StatusOK, resp_json{
|
|
Status: "Success",
|
|
Logs: lista,
|
|
})
|
|
}
|
|
|
|
func player_data(c echo.Context) error {
|
|
userSession, err := ValidSession(c)
|
|
if err != nil {
|
|
return c.JSON(http.StatusUnauthorized, resp_json{
|
|
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 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 {
|
|
vida = fmt.Sprintf("%v/%v", vd, vdm)
|
|
return c.JSON(http.StatusOK, resp_json{
|
|
Status: "Success",
|
|
Foto: foto,
|
|
PlayerName: playername,
|
|
Conhecimento: &conhecimento,
|
|
Level: &level,
|
|
Idade: &idade,
|
|
Altura: &altura,
|
|
Vida: vida,
|
|
Destresa: &destresa,
|
|
Inteligencia: &inteligencia,
|
|
Força: &força,
|
|
Constituição: &constituição,
|
|
Cárisma: &cárisma,
|
|
Inventario: &inventario,
|
|
Descrição: descrição,
|
|
})
|
|
}
|
|
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 {
|
|
userSession, err := ValidSession(c)
|
|
if err != nil {
|
|
return c.JSON(http.StatusUnauthorized, resp_json{
|
|
Status: "Error",
|
|
Message: err.Error(),
|
|
})
|
|
}
|
|
updown := c.Param("updown")
|
|
atb := c.Param("atb")
|
|
var sinal string
|
|
|
|
switch updown {
|
|
case "up":
|
|
sinal = "+"
|
|
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{
|
|
"vida": fmt.Sprintf("UPDATE players SET vida = vida %s 1 WHERE id=?;", sinal),
|
|
"level": fmt.Sprintf("UPDATE players SET level = level %s 1 WHERE id=?;", sinal),
|
|
"idade": fmt.Sprintf("UPDATE players SET idade = idade %s 1 WHERE id=?;", sinal),
|
|
"conhecimento": fmt.Sprintf("UPDATE players SET conhecimento = conhecimento %s 1 WHERE id=?;", sinal),
|
|
"força": fmt.Sprintf("UPDATE players SET força = força %s 1 WHERE id=?;", sinal),
|
|
"destresa": fmt.Sprintf("UPDATE players SET destresa = destresa %s 1 WHERE id=?;", sinal),
|
|
"constituição": fmt.Sprintf("UPDATE players SET constituição = constituição %s 1 WHERE id=?;", sinal),
|
|
"inteligencia": fmt.Sprintf("UPDATE players SET inteligencia = inteligencia %s 1 WHERE id=?;", sinal),
|
|
"cárisma": fmt.Sprintf("UPDATE players SET cárisma = cárisma %s 1 WHERE id=?;", sinal),
|
|
}
|
|
|
|
query, ok := updateList[atb]
|
|
if !ok {
|
|
return c.JSON(http.StatusBadRequest, resp_json{
|
|
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{
|
|
Status: "Success",
|
|
Message: sinal + "1 em " + atb,
|
|
})
|
|
}
|
|
|
|
func player_updateInputs(c echo.Context) error {
|
|
userSession, err := ValidSession(c)
|
|
if err != nil {
|
|
return c.JSON(http.StatusUnauthorized, resp_json{
|
|
Status: "Error",
|
|
Message: err.Error(),
|
|
})
|
|
}
|
|
|
|
var lista []string
|
|
|
|
vida := c.FormValue("vida")
|
|
nome := c.FormValue("nome")
|
|
altura := c.FormValue("altura")
|
|
inv := c.FormValue("inventario")
|
|
|
|
if vida != "" {
|
|
_, err = db.Exec("UPDATE players SET vida=?, vida_maxima=? WHERE id=?;", vida, vida, userSession["user_id"])
|
|
if err != nil {
|
|
log.Println(err)
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
Status: "Error",
|
|
Message: "algo deu errado ao alterar sua vida.",
|
|
})
|
|
}
|
|
lista = append(lista, "vida")
|
|
}
|
|
|
|
if nome != "" {
|
|
_, err = db.Exec("UPDATE players SET nome=? WHERE id=?;", nome, userSession["user_id"])
|
|
if err != nil {
|
|
log.Println(err)
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
Status: "Error",
|
|
Message: "algo deu errado ao alterar seu nome.",
|
|
})
|
|
}
|
|
lista = append(lista, "nome")
|
|
}
|
|
|
|
if altura != "" {
|
|
_, err = db.Exec("UPDATE players SET altura=? WHERE id=?;", altura, userSession["user_id"])
|
|
if err != nil {
|
|
log.Println(err)
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
Status: "Error",
|
|
Message: "algo deu errado ao alterar sua altura.",
|
|
})
|
|
}
|
|
lista = append(lista, "altura")
|
|
}
|
|
|
|
if inv != "" {
|
|
_, err = db.Exec("UPDATE players SET inventario=? WHERE id=?;", inv, userSession["user_id"])
|
|
if err != nil {
|
|
log.Println(err)
|
|
return c.JSON(http.StatusInternalServerError, resp_json{
|
|
Status: "Error",
|
|
Message: "algo deu errado ao alterar o tamanho do seu inventario.",
|
|
})
|
|
}
|
|
lista = append(lista, "inventario")
|
|
}
|
|
|
|
if len(lista) <= 0 {
|
|
return c.JSON(http.StatusUnauthorized, resp_json{
|
|
Status: "Error",
|
|
Message: "você é obrigado a alguma informação seu cabaço.",
|
|
})
|
|
}
|
|
return c.JSON(http.StatusOK, resp_json{
|
|
Status: "Success",
|
|
Message: fmt.Sprintf("você mudou as seguintes informaçôes: %s", lista),
|
|
})
|
|
}
|