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

44 lines
1.2 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
"github.com/notherealmarco/WASAPhoto/service/api/reqcontext"
2022-11-18 17:18:46 +01:00
"github.com/notherealmarco/WASAPhoto/service/database"
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
func SendAuthorizationError(f func(db database.AppDatabase, uid string) (reqcontext.AuthStatus, error), uid string, db database.AppDatabase, w http.ResponseWriter, notFoundStatus int) bool {
2022-11-18 17:18:46 +01:00
auth, err := f(db, uid)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
// todo: log error and write it to the response
return false
}
if auth == reqcontext.UNAUTHORIZED {
w.WriteHeader(http.StatusUnauthorized)
return false
}
if auth == reqcontext.FORBIDDEN {
w.WriteHeader(http.StatusForbidden)
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 {
w.WriteHeader(notFoundStatus)
2022-11-18 18:58:12 +01:00
return false
}
2022-11-18 17:18:46 +01:00
return true
}