2023-10-22 17:46:46 +02:00
|
|
|
package endpoint
|
|
|
|
|
2023-10-26 17:26:09 +02:00
|
|
|
import (
|
|
|
|
"git.jmbit.de/jmb/patchman/server/database"
|
2023-10-26 18:31:57 +02:00
|
|
|
"git.jmbit.de/jmb/patchman/server/utils"
|
2023-10-26 17:26:09 +02:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
2023-10-22 17:46:46 +02:00
|
|
|
|
|
|
|
type Registration struct {
|
2023-10-26 17:26:09 +02:00
|
|
|
hostname string
|
|
|
|
token string
|
|
|
|
secret string
|
2023-10-22 17:46:46 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func Register(c *gin.Context) {
|
|
|
|
var requestData Registration
|
2023-10-26 17:26:09 +02:00
|
|
|
var usedToken database.RegistrationToken
|
|
|
|
now := time.Now()
|
2023-10-26 18:31:57 +02:00
|
|
|
err := c.ShouldBindJSON(&requestData)
|
|
|
|
utils.HandleError(err, http.StatusBadRequest, "Could not parse JSON", c)
|
2023-10-26 17:26:09 +02:00
|
|
|
|
|
|
|
// Validate registration token
|
|
|
|
hashedToken, err := bcrypt.GenerateFromPassword([]byte(requestData.token), bcrypt.DefaultCost)
|
|
|
|
usedToken.Hash = string(hashedToken)
|
2023-10-26 18:31:57 +02:00
|
|
|
utils.HandleError(err, http.StatusBadRequest, "Could not hash token", c)
|
|
|
|
|
2023-10-26 17:26:09 +02:00
|
|
|
result := database.DB.First(&usedToken)
|
2023-10-26 18:31:57 +02:00
|
|
|
utils.HandleError(result.Error, http.StatusBadRequest, "Could not validate registration Token", c)
|
2023-10-22 17:46:46 +02:00
|
|
|
|
2023-10-26 17:26:09 +02:00
|
|
|
// create Endpoint struct
|
|
|
|
hashedSecret, err := bcrypt.GenerateFromPassword([]byte(requestData.secret), bcrypt.DefaultCost)
|
2023-10-26 18:31:57 +02:00
|
|
|
utils.HandleError(err, http.StatusBadRequest, "Could not hash secret", c)
|
|
|
|
|
2023-10-26 17:26:09 +02:00
|
|
|
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)
|
2023-10-26 18:31:57 +02:00
|
|
|
utils.HandleError(result.Error, http.StatusBadRequest, "Could not create Endpoint DB entry", c)
|
|
|
|
|
2023-10-26 21:32:21 +02:00
|
|
|
c.JSON(http.StatusCreated, gin.H{"uuid": newEndpoint.ID})
|
2023-10-26 17:26:09 +02:00
|
|
|
|
2023-10-22 17:46:46 +02:00
|
|
|
}
|