graphicek/server/middleware/auth.go

57 lines
958 B
Go

package middleware
import (
"basic-sensor-receiver/app"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
func LoginAuthMiddleware(server *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
if !server.Config.AuthEnabled {
c.Next()
return
}
_, err := server.Services.Auth.FromContext(c)
if err != nil {
c.AbortWithError(http.StatusUnauthorized, err)
return
}
c.Next()
}
}
func KeyAuthMiddleware(server *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
sensorParam := c.Param("sensor")
sensorId, err := strconv.ParseInt(sensorParam, 10, 64)
if err != nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
sensor, err := server.Services.Sensors.GetById(sensorId)
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
if c.GetHeader("authorization") != "Bearer "+sensor.AuthKey {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Next()
}
}