103 lines
2.2 KiB
Go
103 lines
2.2 KiB
Go
package routes
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
"orbits-server/internal/server/api/response"
|
|
"orbits-server/internal/server/database"
|
|
"orbits-server/internal/shared/security"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const (
|
|
accessKeyLen = 32
|
|
)
|
|
|
|
func RegisterApiRoutes(api *gin.RouterGroup, db *gorm.DB) {
|
|
// prefix: api
|
|
|
|
// define subroute with key
|
|
// /api/key
|
|
key := api.Group("/key")
|
|
|
|
/*
|
|
key.GET("/:key", func(c *gin.Context) {
|
|
|
|
})
|
|
*/
|
|
|
|
key.POST("/create", func(c *gin.Context) {
|
|
var body keyRequestBody
|
|
|
|
err := c.ShouldBindBodyWithJSON(&body)
|
|
if err != nil {
|
|
slog.Error("failed to bind body to json", "error", err)
|
|
c.JSON(http.StatusBadRequest, response.BasicResponse{
|
|
Msg: "invalid JSON",
|
|
})
|
|
return
|
|
}
|
|
|
|
keyContent := security.GenerateChars(accessKeyLen)
|
|
hash, err := security.HashKey(keyContent)
|
|
if err != nil {
|
|
slog.Error("failed to generate a hash for the key", "error", err)
|
|
c.JSON(http.StatusInternalServerError, response.BasicResponse{
|
|
Msg: response.IntErrMes,
|
|
})
|
|
return
|
|
}
|
|
|
|
keyRecord := database.BuildKeyRecord(hash, body.Name, body.ExpiresAt)
|
|
|
|
if err := database.CreateKey(db, &keyRecord); err != nil {
|
|
slog.Error("failed to insert key into the database", "error", err)
|
|
c.JSON(http.StatusInternalServerError, response.BasicResponse{
|
|
Msg: response.IntErrMes,
|
|
})
|
|
return
|
|
}
|
|
|
|
slog.Info("saved key to database")
|
|
|
|
c.JSON(http.StatusCreated, response.BasicResponse{
|
|
Msg: "key has succesfully been created and saved",
|
|
Data: keyContent,
|
|
})
|
|
})
|
|
|
|
key.GET("/verify", func(c *gin.Context) {
|
|
|
|
})
|
|
|
|
key.DELETE("/:key", func(c *gin.Context) {
|
|
|
|
})
|
|
|
|
// define the control route on the api
|
|
// /api/control
|
|
ctl := api.Group("/control")
|
|
// Display the information on what is going on at the moment
|
|
ctl.GET("/command", func(c *gin.Context) {
|
|
state, err := database.LatestState(db)
|
|
if err != nil {
|
|
slog.Error("unable to determine state", "error", err)
|
|
c.JSON(http.StatusInternalServerError, response.BasicResponse{
|
|
Msg: response.IntErrMes,
|
|
})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, response.BasicResponse{
|
|
Msg: response.OkMes,
|
|
Data: state,
|
|
})
|
|
})
|
|
|
|
ctl.PATCH("/command", func(c *gin.Context) {
|
|
|
|
})
|
|
}
|