Files
rpgzrox/back_end/func_db.go
2025-07-11 10:08:28 -03:00

146 lines
3.2 KiB
Go

package main
import (
"Helena_de_troia/config_data"
"database/sql"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/go-sql-driver/mysql"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
)
func sessionCookie(id int, player string) (*http.Cookie, error) {
sessionID := uuid.New().String()
sessionInfo := map[string]interface{}{
"user_id": id,
"playerName": player,
}
load_data, _ := config_data.FileAuthGET()
sessionTime, err := strconv.Atoi(load_data["sessionDuration"].(string))
if err != nil {
log.Fatal("sessionTime não foi encontrado ou não é um valor int, verifique o arquivo de configurações e tente novamente")
}
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, time.Duration(sessionTime)*time.Hour).Err()
if err != nil {
log.Fatal(err)
}
cookie := &http.Cookie{
Name: cookieName,
Value: sessionID,
Path: "/",
Domain: load_data["siteUnlock"].(string),
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteNoneMode,
Expires: time.Now().Add(time.Duration(sessionTime) * time.Hour),
}
return cookie, nil
}
func delCookie(c echo.Context, sessionID string) error {
cookie := &http.Cookie{
Name: cookieName,
Value: "",
Path: "/",
MaxAge: -1,
}
err := redisCL.Del(ctx, sessionID).Err()
if err != nil {
log.Println(sessionID + "não era um cookie valido")
}
c.SetCookie(cookie)
return 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)
}
defer rows.Close()
log.Printf("tabela %s foi criada.\n", a)
}
}
log.Println("verificação comcluida.")
return nil
}
func ValidSession(c echo.Context) (map[string]string, error) {
cookie, err := c.Cookie(cookieName)
if err != nil {
return nil, fmt.Errorf("sessão não existe, faça login.")
}
sessionID := cookie.Value
dataSession, err := redisCL.HGetAll(ctx, sessionID).Result()
if err != nil {
delCookie(c, sessionID)
return nil, fmt.Errorf("sessão invalida ou expirada.")
}
return dataSession, nil
}