graphicek/server/middleware/auth.go

57 lines
958 B
Go
Raw Permalink Normal View History

2022-08-21 20:51:14 +02:00
package middleware
import (
"basic-sensor-receiver/app"
"net/http"
2022-08-28 11:56:03 +02:00
"strconv"
2022-08-21 20:51:14 +02:00
"github.com/gin-gonic/gin"
)
func LoginAuthMiddleware(server *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
2024-03-31 18:33:56 +02:00
if !server.Config.AuthEnabled {
c.Next()
return
}
2022-08-21 20:51:14 +02:00
_, 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) {
2022-08-28 11:56:03 +02:00
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 {
2022-08-21 20:51:14 +02:00
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Next()
}
}