Files
lambdaiot-core/internal/handler/handlers.go
2025-12-28 13:24:16 +01:00

61 lines
1.5 KiB
Go

package handler
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// Health returns basic service health
func Health(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
// Hello returns a simple greeting
func Hello(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "hello from lambda-iot core"})
}
// Login issues a JWT token for demo purposes
func Login(c *gin.Context) {
var req struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.BindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid json"})
return
}
// demo credentials
if req.Username != "admin" || req.Password != "password" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
// create token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": req.Username,
"exp": time.Now().Add(time.Hour).Unix(),
})
secret := "secret"
if s := c.GetHeader("X-JWT-SECRET"); s != "" {
secret = s
}
signed, err := token.SignedString([]byte(secret))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "could not sign token"})
return
}
c.JSON(http.StatusOK, gin.H{"token": signed})
}
// Protected requires a valid JWT and returns the token claims
func Protected(c *gin.Context) {
if v, ok := c.Get("claims"); ok {
c.JSON(http.StatusOK, gin.H{"claims": v})
return
}
c.JSON(http.StatusUnauthorized, gin.H{"error": "no claims"})
}