feat: add services and separate further

This commit is contained in:
2026-04-29 13:25:38 +02:00
parent 6c28aea655
commit 8f6b1efea0
16 changed files with 318 additions and 168 deletions
+3
View File
@@ -31,6 +31,9 @@ func Kickoff(logger *slog.Logger, env bootstrap.Environment, db *gorm.DB) {
api := r.Group("/api")
routes.RegisterApiRoutes(api, db)
// also register the 2 api subroutes
routes.RegisterKeyRoutes(api, db)
routes.RegisterCtrlRoutes(api, db)
file := r.Group("/file")
routes.RegisterFileRoutes(file, env, db)
@@ -1,8 +1,8 @@
package routes
package assets
import "time"
type keyRequestBody struct {
type KeyRequestBody struct {
Name string `json:"name"`
// post request must contain valid: RFC3339 timestamp
ExpiresAt time.Time `json:"expiresAt"`
+45
View File
@@ -0,0 +1,45 @@
package assets
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
)
const (
OkMes string = "OK"
IntErrMes string = "An internal error occured, contact your administrator"
)
type BasicResponse struct {
Msg string `json:"msg"`
Data any `json:"data"`
}
// we swap out the hash for the keycontent
type KeyResponse struct {
ID int `json:"id"`
MetaName string `json:"metaName"`
KeyName string `json:"keyName"`
KeyContent string `json:"keyContent"`
Revoked bool `json:"revoked"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ExpiresAt time.Time `json:"expiresAt"`
}
type FileResponse struct {
ID int `json:"id"`
MetaName string `json:"metaName"`
FileName string `json:"fileName"`
MediaType string `json:"mediaType"`
CreatedAt time.Time `json:"createdAt"`
ExpiresAt time.Time `json:"expiresAt"`
}
func InternalErrorResponse(c *gin.Context) {
c.JSON(http.StatusInternalServerError, BasicResponse{
Msg: IntErrMes,
})
}
+3 -3
View File
@@ -3,7 +3,7 @@ package middleware
import (
"log/slog"
"net/http"
"orbits-server/internal/server/api/response"
"orbits-server/internal/server/api/assets"
"strings"
"time"
@@ -42,7 +42,7 @@ func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authorizationHeader := c.GetHeader("Authorization")
if len(authorizationHeader) == 0 {
c.AbortWithStatusJSON(http.StatusUnauthorized, response.BasicResponse{
c.AbortWithStatusJSON(http.StatusUnauthorized, assets.BasicResponse{
Msg: "Authorization header is required",
})
return
@@ -52,7 +52,7 @@ func AuthMiddleware() gin.HandlerFunc {
// The header must be a specific format, 0 being the bearer text and 1 being the token itself, making it 2 pieces total
// In the following if statement we verify both parts if the part after Bearer is empty its only 1 part for example
if len(headerParts) != 2 || headerParts[0] != "Bearer" {
c.AbortWithStatusJSON(http.StatusUnauthorized, response.BasicResponse{
c.AbortWithStatusJSON(http.StatusUnauthorized, assets.BasicResponse{
Msg: "Authorization header is invalid",
})
return
-11
View File
@@ -1,11 +0,0 @@
package response
const (
OkMes string = "OK"
IntErrMes string = "An internal error occured, contact your administrator"
)
type BasicResponse struct {
Msg string `json:"msg"`
Data any `json:"data"`
}
+2 -88
View File
@@ -1,102 +1,16 @@
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) {
api.GET("/version", 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) {
api.GET("/codename", func(c *gin.Context) {
})
}
+36
View File
@@ -0,0 +1,36 @@
package routes
import (
"log/slog"
"net/http"
"orbits-server/internal/server/api/assets"
"orbits-server/internal/server/service"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func RegisterCtrlRoutes(api *gin.RouterGroup, db *gorm.DB) {
ctrlService := service.NewControlService(db)
// define the control route on the api
// /api/control
ctrl := api.Group("/control")
// Display the information on what is going on at the moment
ctrl.GET("/command", func(c *gin.Context) {
command, err := ctrlService.ListLatestCommand()
if err != nil {
slog.Error("unable to determine state", "error", err)
assets.InternalErrorResponse(c)
return
}
c.JSON(http.StatusOK, assets.BasicResponse{
Msg: assets.OkMes,
Data: command,
})
})
ctrl.PATCH("/command", func(c *gin.Context) {
})
}
+19 -43
View File
@@ -1,12 +1,11 @@
package routes
import (
"errors"
"log/slog"
"net/http"
"orbits-server/internal/server/api/response"
"orbits-server/internal/server/api/assets"
"orbits-server/internal/server/bootstrap"
"orbits-server/internal/server/database"
"orbits-server/internal/server/service"
"path/filepath"
"github.com/gin-gonic/gin"
@@ -14,6 +13,7 @@ import (
)
func RegisterFileRoutes(file *gin.RouterGroup, env bootstrap.Environment, db *gorm.DB) {
fileService := service.NewFileService(db, env)
// prefix: file
// for example: /file/<file-name>
@@ -30,7 +30,7 @@ func RegisterFileRoutes(file *gin.RouterGroup, env bootstrap.Environment, db *go
fh, err := c.FormFile("file")
if err != nil {
slog.Debug("no file or file headers provided on the request", "error", err)
c.JSON(http.StatusBadRequest, response.BasicResponse{
c.JSON(http.StatusBadRequest, assets.BasicResponse{
Msg: "a file is required",
})
return
@@ -39,35 +39,15 @@ func RegisterFileRoutes(file *gin.RouterGroup, env bootstrap.Environment, db *go
stream, err := fh.Open()
if err != nil {
slog.Error("failed to a reader stream")
c.JSON(http.StatusInternalServerError, response.BasicResponse{
Msg: response.IntErrMes,
})
assets.InternalErrorResponse(c)
return
}
defer stream.Close()
fileRecord, err := database.BuildFileRecord(stream, fh.Filename, env.ContentDirectory)
fileRecord, err := fileService.Create(stream, fh.Filename)
if err != nil {
slog.Error("failed to enroll file to the database", "error", err)
c.JSON(http.StatusInternalServerError, response.BasicResponse{
Msg: response.IntErrMes,
})
return
}
if err := database.CreateFile(db, &fileRecord); err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
slog.Debug("discarding file, its a checksum duplicate", "error", err)
c.JSON(http.StatusConflict, response.BasicResponse{
Msg: "file already exists",
})
} else {
// log the failure to the std
slog.Error("failed to insert filedata to the database", "error", err)
c.JSON(http.StatusInternalServerError, response.BasicResponse{
Msg: response.IntErrMes,
})
}
assets.InternalErrorResponse(c)
return
}
@@ -76,20 +56,15 @@ func RegisterFileRoutes(file *gin.RouterGroup, env bootstrap.Environment, db *go
slog.Error("failed to save to disk, rolling back database", "error", err)
// rollback db if the write has failed
err = database.DeleteFileByID(db, fileRecord.ID)
if err != nil {
slog.Error("failed to remove the database record", "error", err)
}
fileService.DeleteByID(fileRecord.ID)
// give the response to the client
c.JSON(http.StatusInternalServerError, response.BasicResponse{
Msg: response.IntErrMes,
})
assets.InternalErrorResponse(c)
return
}
slog.Info("saved file to local filesystem and database")
c.JSON(http.StatusCreated, response.BasicResponse{
c.JSON(http.StatusCreated, assets.BasicResponse{
Msg: "file has succesfully been uploaded",
Data: fileRecord,
})
@@ -98,31 +73,32 @@ func RegisterFileRoutes(file *gin.RouterGroup, env bootstrap.Environment, db *go
// delete route
file.DELETE("/:filename", func(c *gin.Context) {
fileParam := c.Param("filename")
fileRecord, err := database.FindFileByName(db, fileParam)
fileRecord, err := fileService.DeleteByName(fileParam)
if err != nil {
slog.Error("file not found", "error", err)
c.JSON(http.StatusNotFound, response.BasicResponse{
c.JSON(http.StatusNotFound, assets.BasicResponse{
Msg: "file was not found",
})
return
}
slog.Info("received a delete request for a file", "file", fileRecord, "filename", fileParam)
c.JSON(http.StatusOK, assets.BasicResponse{
Msg: "file deleted succesfully",
})
})
// define a route to check what is registered
file.GET("/available", func(c *gin.Context) {
files, err := database.ListFiles(db)
files, err := fileService.ListFiles()
if err != nil {
slog.Error("failed to retrieve available files", "error", err)
c.JSON(http.StatusInternalServerError, response.BasicResponse{
Msg: response.IntErrMes,
})
assets.InternalErrorResponse(c)
return
}
c.JSON(http.StatusOK, response.BasicResponse{
Msg: response.OkMes,
c.JSON(http.StatusOK, assets.BasicResponse{
Msg: assets.OkMes,
Data: files,
})
})
+48
View File
@@ -0,0 +1,48 @@
package routes
import (
"log/slog"
"net/http"
"orbits-server/internal/server/api/assets"
"orbits-server/internal/server/service"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func RegisterKeyRoutes(api *gin.RouterGroup, db *gorm.DB) {
keyService := service.NewKeyService(db)
// prefix: api
// define subroute with key
// /api/key
key := api.Group("/key")
key.POST("/create", func(c *gin.Context) {
var body assets.KeyRequestBody
if err := c.ShouldBindJSON(&body); err != nil {
slog.Error("failed to bind body to json", "error", err)
assets.InternalErrorResponse(c)
return
}
keyResponse, err := keyService.Create(body.Name, body.ExpiresAt)
if err != nil {
slog.Error("failed to create key", "error", err)
assets.InternalErrorResponse(c)
return
}
slog.Info("saved key to database")
c.JSON(http.StatusCreated, assets.BasicResponse{
Msg: "key has succesfully been created and saved",
Data: keyResponse,
})
})
key.DELETE("/:key", func(c *gin.Context) {
})
}