add update endpoint
This commit is contained in:
@@ -2,6 +2,7 @@ package controllers
|
||||
|
||||
import (
|
||||
"ccsecrets/models"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
@@ -12,7 +13,7 @@ import (
|
||||
type StoreInput struct {
|
||||
RoleId int `json:"roleId"`
|
||||
DeviceName string `json:"deviceName"`
|
||||
DeviceCategory string `json:"devicCategory"`
|
||||
DeviceCategory string `json:"deviceCategory"`
|
||||
UserName string `json:"userName" binding:"required"`
|
||||
SecretValue string `json:"secretValue" binding:"required"`
|
||||
}
|
||||
@@ -70,3 +71,67 @@ func StoreSecret(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "secret stored successfully"})
|
||||
}
|
||||
|
||||
func UpdateSecret(c *gin.Context) {
|
||||
var err error
|
||||
var input StoreInput
|
||||
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("UpdateSecret received JSON input '%v'\n", input)
|
||||
|
||||
// TODO - verify that the user role is not readonly
|
||||
|
||||
// Populate fields
|
||||
s := models.Secret{}
|
||||
s.UserName = input.UserName
|
||||
s.DeviceName = input.DeviceName
|
||||
s.DeviceCategory = input.DeviceCategory
|
||||
|
||||
// Default role ID is 1 if not defined
|
||||
if input.RoleId != 0 {
|
||||
s.RoleId = input.RoleId
|
||||
} else {
|
||||
s.RoleId = 1
|
||||
}
|
||||
|
||||
// Confirm that the secret already exists
|
||||
checkExists, err := models.GetSecrets(&s)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if len(checkExists) == 0 {
|
||||
err = errors.New("UpdateSecret could not find existing secret to update")
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
} else if len(checkExists) == 1 {
|
||||
// Set the secret id with the one retrieved from the database
|
||||
s.SecretId = checkExists[0].SecretId
|
||||
|
||||
// Encrypt secret
|
||||
s.Secret = input.SecretValue
|
||||
_, err = s.EncryptSecret()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"Error encrypting secret": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
_, err = s.UpdateSecret()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"Error saving secret": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "secret updated successfully"})
|
||||
} else {
|
||||
err = errors.New("UpdateSecret found multiple secrets matching input data, be more specific")
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user