Files
smt/controllers/retrieve_secrets.go
Nathan Coad 747487b764
All checks were successful
continuous-integration/drone/push Build is passing
rename project to smt
2023-04-04 12:47:50 +10:00

107 lines
2.4 KiB
Go

package controllers
import (
"smt/models"
"smt/utils/token"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
type RetrieveInput struct {
DeviceName string `json:"deviceName"`
DeviceCategory string `json:"deviceCategory"`
}
func RetrieveSecret(c *gin.Context) {
var input RetrieveInput
// Validate the input matches our struct
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
log.Printf("RetrieveSecret received JSON input '%v'\n", input)
// Get the user and role id of the requestor
user_id, err := token.ExtractTokenID(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
u, err := models.GetUserRoleByID(user_id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Populate fields
s := models.Secret{}
s.RoleId = u.RoleId
s.DeviceName = input.DeviceName
s.DeviceCategory = input.DeviceCategory
results, err := models.GetSecrets(&s)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if len(results) == 1 {
// output results as json
c.JSON(http.StatusOK, gin.H{"message": "success", "data": results})
} else if len(results) > 1 {
c.JSON(http.StatusBadRequest, gin.H{"error": "found multiple matching secrets, use retrieveMultiple instead"})
return
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": "found no matching secrets"})
return
}
}
func RetrieveMultpleSecrets(c *gin.Context) {
var input RetrieveInput
// Validate the input matches our struct
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
log.Printf("StoreSecret received JSON input '%v'\n", input)
// Get the user and role id of the requestor
user_id, err := token.ExtractTokenID(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
u, err := models.GetUserRoleByID(user_id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Populate fields
s := models.Secret{}
s.RoleId = u.RoleId
s.DeviceName = input.DeviceName
s.DeviceCategory = input.DeviceCategory
results, err := models.GetSecrets(&s)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// output results as json
c.JSON(http.StatusOK, gin.H{"message": "success", "data": results})
}