104 lines
2.3 KiB
Go
104 lines
2.3 KiB
Go
package controllers
|
|
|
|
import (
|
|
"ccsecrets/models"
|
|
"ccsecrets/utils/token"
|
|
"errors"
|
|
"fmt"
|
|
"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
|
|
}
|
|
fmt.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 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": errors.New("found multiple matching secrets, use retrieveMultiple instead")})
|
|
return
|
|
}
|
|
|
|
// output results as json
|
|
c.JSON(http.StatusOK, gin.H{"message": "success", "data": results})
|
|
}
|
|
|
|
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
|
|
}
|
|
fmt.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})
|
|
}
|