2021-06-01 10:51:35 +02:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
|
2023-10-23 21:40:10 +02:00
|
|
|
"codeberg.org/genofire/golang-lib/web"
|
2021-06-01 10:51:35 +02:00
|
|
|
)
|
|
|
|
|
2021-06-01 18:44:09 +02:00
|
|
|
// MiddlewareLogin if user id in session for golang-gin
|
2021-06-01 10:51:35 +02:00
|
|
|
func MiddlewareLogin(ws *web.Service) gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
_, ok := GetCurrentUserID(c)
|
|
|
|
if !ok {
|
|
|
|
c.Abort()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-01 18:44:09 +02:00
|
|
|
// MiddlewarePermissionParamUUID if user has access to obj, check access by uuid in golang-gin url param uuid
|
2021-06-01 10:51:35 +02:00
|
|
|
func MiddlewarePermissionParamUUID(ws *web.Service, obj HasPermission) gin.HandlerFunc {
|
|
|
|
return MiddlewarePermissionParam(ws, obj, "uuid")
|
|
|
|
}
|
2021-06-01 18:44:09 +02:00
|
|
|
|
|
|
|
// MiddlewarePermissionParam if user has access to obj, check access in golang-gin url by param
|
2021-06-01 10:51:35 +02:00
|
|
|
func MiddlewarePermissionParam(ws *web.Service, obj HasPermission, param string) gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
userID, ok := GetCurrentUserID(c)
|
|
|
|
if !ok {
|
|
|
|
c.Abort()
|
|
|
|
}
|
|
|
|
objID, err := uuid.Parse(c.Params.ByName(param))
|
|
|
|
if err != nil {
|
|
|
|
c.JSON(http.StatusUnauthorized, web.HTTPError{
|
2021-07-22 18:16:05 +02:00
|
|
|
Message: web.ErrAPIInvalidRequestFormat.Error(),
|
2021-06-01 10:51:35 +02:00
|
|
|
Error: err.Error(),
|
|
|
|
})
|
|
|
|
c.Abort()
|
|
|
|
}
|
2021-09-12 22:41:33 +02:00
|
|
|
d, err := obj.HasPermission(ws.DB, userID, objID)
|
2021-06-01 10:51:35 +02:00
|
|
|
if err != nil {
|
|
|
|
c.JSON(http.StatusUnauthorized, web.HTTPError{
|
2021-07-22 18:16:05 +02:00
|
|
|
Message: ErrAPINoPermission.Error(),
|
2021-06-01 10:51:35 +02:00
|
|
|
Error: err.Error(),
|
|
|
|
})
|
|
|
|
c.Abort()
|
|
|
|
}
|
2021-09-12 22:41:33 +02:00
|
|
|
if d == nil {
|
|
|
|
c.JSON(http.StatusNotFound, web.HTTPError{
|
|
|
|
Message: web.ErrAPINotFound.Error(),
|
|
|
|
})
|
|
|
|
c.Abort()
|
|
|
|
}
|
2021-06-01 10:51:35 +02:00
|
|
|
}
|
|
|
|
}
|