WASAPhoto/service/api/authorization/auth-manager.go

62 lines
1.7 KiB
Go
Raw Normal View History

2022-11-18 13:05:40 +01:00
package authorization
import (
"errors"
2022-11-18 17:18:46 +01:00
"net/http"
2022-11-18 13:05:40 +01:00
2022-11-20 19:53:24 +01:00
"github.com/notherealmarco/WASAPhoto/service/api/helpers"
2022-11-18 13:05:40 +01:00
"github.com/notherealmarco/WASAPhoto/service/api/reqcontext"
2022-11-18 17:18:46 +01:00
"github.com/notherealmarco/WASAPhoto/service/database"
2022-11-20 19:53:24 +01:00
"github.com/sirupsen/logrus"
2022-11-18 13:05:40 +01:00
)
func BuildAuth(header string) (reqcontext.Authorization, error) {
auth, err := BuildBearer(header)
if err != nil {
if err.Error() == "invalid authorization header" {
return nil, errors.New("method not supported") // todo: better error description
}
return nil, err
}
return auth, nil
}
2022-11-18 17:18:46 +01:00
2022-11-20 19:53:24 +01:00
func SendAuthorizationError(f func(db database.AppDatabase, uid string) (reqcontext.AuthStatus, error), uid string, db database.AppDatabase, w http.ResponseWriter, l logrus.FieldLogger, notFoundStatus int) bool {
2022-11-18 17:18:46 +01:00
auth, err := f(db, uid)
if err != nil {
2022-11-20 19:53:24 +01:00
helpers.SendInternalError(err, "Authorization error", w, l)
2022-11-18 17:18:46 +01:00
return false
}
if auth == reqcontext.UNAUTHORIZED {
2022-11-20 19:53:24 +01:00
helpers.SendStatus(http.StatusUnauthorized, w, "Unauthorized", l)
2022-11-18 17:18:46 +01:00
return false
}
if auth == reqcontext.FORBIDDEN {
2022-11-20 19:53:24 +01:00
helpers.SendStatus(http.StatusForbidden, w, "Forbidden", l)
2022-11-18 17:18:46 +01:00
return false
}
2022-11-18 18:58:12 +01:00
// requested user is not found -> 404 as the resource is not found
if auth == reqcontext.USER_NOT_FOUND {
2022-11-20 19:53:24 +01:00
helpers.SendStatus(notFoundStatus, w, "Resource not found", l)
2022-11-18 18:58:12 +01:00
return false
}
2022-11-18 17:18:46 +01:00
return true
}
func SendErrorIfNotLoggedIn(f func(db database.AppDatabase) (reqcontext.AuthStatus, error), db database.AppDatabase, w http.ResponseWriter, l logrus.FieldLogger) bool {
auth, err := f(db)
if err != nil {
helpers.SendInternalError(err, "Authorization error", w, l)
return false
}
if auth == reqcontext.UNAUTHORIZED {
helpers.SendStatus(http.StatusUnauthorized, w, "Unauthorized", l)
return false
}
return true
}