aboutsummaryrefslogtreecommitdiff
path: root/api/main.go
blob: ebae5d1a0feefaaec43a3843c6d68d04c50fb044 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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")
}