68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
"backend/models"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func (r *NodeHandler) LoginHandler(c *gin.Context) {
|
|
log.Println("trying to login")
|
|
r.Repo.LoginHandler(c)
|
|
}
|
|
|
|
func GenerateSecureKey() (string, error) {
|
|
bytes := make([]byte, 32) // 256 bits
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(bytes), nil
|
|
}
|
|
|
|
func (r *NodeHandler) CreateApiKeyHandler(c *gin.Context) {
|
|
|
|
log.Println("trying to create key")
|
|
newApiKey, err := GenerateSecureKey()
|
|
|
|
if err != nil {
|
|
log.Printf("Generate API key error: %v", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "key creation error"})
|
|
return
|
|
}
|
|
|
|
var key models.CreateApiKeyResponse
|
|
|
|
key, err = r.Repo.CreateApiKeyHandler(c, newApiKey)
|
|
|
|
if err != nil {
|
|
log.Printf("CreateApiKeyHandler error: %v", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "insert new api key error"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, key)
|
|
}
|
|
|
|
func (h *NodeHandler) HandleRetrieveApiKeys(c *gin.Context) {
|
|
|
|
log.Println("All api keys retrieve request")
|
|
|
|
apiKeys := make([]models.ApiKey, 0)
|
|
|
|
apiKeys, err := h.Repo.RetriveApiKeyList()
|
|
|
|
if err != nil {
|
|
log.Printf("Request error on retrieving api keys: %v", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "error retrieving api keys"})
|
|
return
|
|
}
|
|
|
|
log.Printf("nb api keys: %v", len(apiKeys))
|
|
|
|
c.JSON(http.StatusOK, apiKeys)
|
|
}
|