package cmd import ( "crypto/sha256" "database/sql" "encoding/hex" "fmt" "log" "net/http" "github.com/gin-gonic/gin" _ "github.com/lib/pq" "github.com/spf13/viper" ) var ( ListenPort = "8080" db *sql.DB DB_Host string DB_Port string DB_User string DB_Pass string DB_Name string ) func server() { log.SetPrefix("[DRAHOOT] ") setPort() if err := getDBInfo(); err != nil { log.Fatalf("INVALID DB INFO: %v\nPlease refer to the example configuration file in the repo at https://git.bulgariu.xyz/raul/drahoot/src/branch/main/sample-config (default config path = ~/.config/drahoot/drahoot.toml)", err) } if err := openDB(); err != nil { log.Fatalf("Error happened trying to connect to database: %v", err) } gin.SetMode(gin.ReleaseMode) r := gin.Default() r.GET("/api/ping", ping) // CRUD for users r.GET("/api/user", getUsers) r.GET("/api/user/:userid", getUser) r.POST("/api/user", createUser) r.DELETE("/api/user/:userid", deleteUser) r.PUT("/api/user/:userid", modifyUser) r.POST("/login", userLogin) // TODO: Finish the following: // CRUD for quizzes // CRUD for quiz questions // CRUD for question answers // CRUD for quiz attempts r.Run(":" + ListenPort) } func setResponse(content any, success bool) response { msg := response{Contents: content, Success: success} return msg } func ping(c *gin.Context) { c.IndentedJSON(http.StatusOK, setResponse("Pong!", true)) } func hashPW(plain string) string { hashedPW := sha256.New() hashedPW.Write([]byte(plain)) sha256hash := hex.EncodeToString(hashedPW.Sum(nil)) return sha256hash } func getDBInfo() error { dbhost := viper.GetString("Server.DB_Host") if dbhost == "" { e := fmt.Errorf("No database IP address present in config file!\n") return e } else { DB_Host = dbhost } dbport := viper.GetString("Server.DB_Port") if dbport == "" { e := fmt.Errorf("No database port present in config file!\n") return e } else { DB_Port = dbport } dbuser := viper.GetString("Server.DB_User") if dbuser == "" { e := fmt.Errorf("No database username present in config file!\n") return e } else { DB_User = dbuser } dbpass := viper.GetString("Server.DB_Pass") if dbpass == "" { e := fmt.Errorf("No database password present in config file!\n") return e } else { DB_Pass = dbpass } dbname := viper.GetString("Server.DB_Name") if dbname == "" { e := fmt.Errorf("No database name present in config file!\n") return e } else { DB_Name = dbname } return nil } func openDB() error { psqlconn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", DB_Host, DB_Port, DB_User, DB_Pass, DB_Name) dba, err := sql.Open("postgres", psqlconn) if err != nil { return err } db = dba return nil } func setPort() { p := viper.GetString("Server.Port") if p != "" { ListenPort = p } }