patchman/server/api/endpoint/register.go

55 lines
1.6 KiB
Go

package endpoint
import (
"git.jmbit.de/jmb/patchman/server/database"
"git.jmbit.de/jmb/patchman/server/utils"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"net/http"
"time"
)
type Registration struct {
hostname string
token string
secret string
}
func Register(c *gin.Context) {
var requestData Registration
var usedToken database.RegistrationToken
now := time.Now()
err := c.ShouldBindJSON(&requestData)
utils.HandleError(err, http.StatusBadRequest, "Could not parse JSON", c)
// Validate registration token
hashedToken, err := bcrypt.GenerateFromPassword([]byte(requestData.token), bcrypt.DefaultCost)
usedToken.Hash = string(hashedToken)
utils.HandleError(err, http.StatusBadRequest, "Could not hash token", c)
result := database.DB.First(&usedToken)
utils.HandleError(result.Error, http.StatusBadRequest, "Could not validate registration Token", c)
// create Endpoint struct
hashedSecret, err := bcrypt.GenerateFromPassword([]byte(requestData.secret), bcrypt.DefaultCost)
utils.HandleError(err, http.StatusBadRequest, "Could not hash secret", c)
newEndpoint := database.Endpoint{
ID: uuid.New(),
Name: requestData.hostname,
LastConnection: &now,
RegisteredDate: &now,
SecretHash: string(hashedSecret),
Enabled: false,
}
// Store Endpoint to Database
database.DB.Create(&newEndpoint)
result = database.DB.First(&usedToken)
utils.HandleError(result.Error, http.StatusBadRequest, "Could not create Endpoint DB entry", c)
c.JSON(http.StatusCreated, gin.H{"uuid": newEndpoint.ID})
}