From 3eafb413a48cde60dea8a7355ee621c6acca952f Mon Sep 17 00:00:00 2001 From: Doog <157747121+doogongithub@users.noreply.github.com> Date: Wed, 21 Feb 2024 22:07:27 -0500 Subject: first commit --- api/main.go | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 api/main.go (limited to 'api/main.go') diff --git a/api/main.go b/api/main.go new file mode 100644 index 0000000..ebae5d1 --- /dev/null +++ b/api/main.go @@ -0,0 +1,99 @@ +package main + +import ( + "net/http" + "crypto/rand" + "encoding/base64" + + "github.com/gin-gonic/gin" +) + +func CORSMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") + c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") + c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") + c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT") + + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(204) + return + } + + c.Next() + } +} + +func generateToken() string { + token := make([]byte, 32) + rand.Read(token) + return base64.StdEncoding.EncodeToString(token) +} + +type User struct { + Username string + Password string +} + +var users = map[string]User{ + "user1": {"user1", "password1"}, +} + +func setupRouter() *gin.Engine { + // Disable Console Color + // gin.DisableConsoleColor() + r := gin.Default() + r.Use(CORSMiddleware()) + + api := r.Group("api/v1") + + api.POST("/auth", func(c *gin.Context) { + username, password, ok := c.Request.BasicAuth() + if !ok { + c.Header("WWW-Authenticate", `Basic realm="Please enter your username and password."`) + c.AbortWithStatus(http.StatusUnauthorized) + return + } + + user, exists := users[username] + + if !exists || user.Password != password { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + + // Generate a simple API token + apiToken := generateToken() + c.JSON(http.StatusOK, gin.H{"token": apiToken}) + }) + + stats := api.Group("stats") + + stats.GET("/", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok"}) + }) + + stats.POST("/", func(c *gin.Context) { + c.JSON(http.StatusCreated, gin.H{"status": "created"}) + }) + + stats.GET("/:uuid", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok", "uuid": c.Param("uuid")}) + }) + + stats.PATCH("/:uuid", func(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) + }) + + stats.DELETE("/:uuid", func(c *gin.Context) { + c.JSON(http.StatusNoContent, gin.H{"status": "No Content"}) + }) + + return r +} + +func main() { + r := setupRouter() + // Listen and Server in 0.0.0.0:8080 + r.Run(":8080") +} -- cgit v1.1