mirror of
https://github.com/safing/portbase
synced 2025-09-02 10:40:39 +00:00
Add authentication failure error messages
This commit is contained in:
parent
38d8a6e5df
commit
5136bf91ed
1 changed files with 14 additions and 9 deletions
|
@ -2,6 +2,7 @@ package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
@ -16,6 +17,10 @@ var (
|
||||||
|
|
||||||
authFnLock sync.Mutex
|
authFnLock sync.Mutex
|
||||||
authFn Authenticator
|
authFn Authenticator
|
||||||
|
|
||||||
|
// ErrAPIAccessDeniedMessage should be returned by Authenticator functions in
|
||||||
|
// order to signify a blocked request, including a error message for the user.
|
||||||
|
ErrAPIAccessDeniedMessage = errors.New("")
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
@ -28,7 +33,7 @@ const (
|
||||||
)
|
)
|
||||||
|
|
||||||
// Authenticator is a function that can be set as the authenticator for the API endpoint. If none is set, all requests will be allowed.
|
// Authenticator is a function that can be set as the authenticator for the API endpoint. If none is set, all requests will be allowed.
|
||||||
type Authenticator func(s *http.Server, r *http.Request) (grantAccess bool, err error)
|
type Authenticator func(s *http.Server, r *http.Request) (err error)
|
||||||
|
|
||||||
// SetAuthenticator sets an authenticator function for the API endpoint. If none is set, all requests will be allowed.
|
// SetAuthenticator sets an authenticator function for the API endpoint. If none is set, all requests will be allowed.
|
||||||
func SetAuthenticator(fn Authenticator) error {
|
func SetAuthenticator(fn Authenticator) error {
|
||||||
|
@ -79,15 +84,15 @@ func authMiddleware(next http.Handler) http.Handler {
|
||||||
}
|
}
|
||||||
|
|
||||||
// get auth decision
|
// get auth decision
|
||||||
grantAccess, err := authenticator(server, r)
|
err = authenticator(server, r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warningf("api: authenticator failed: %s", err)
|
if errors.Is(err, ErrAPIAccessDeniedMessage) {
|
||||||
http.Error(w, "Bad Request: Could not identify client", http.StatusBadRequest)
|
log.Warningf("api: denying api access to %s", r.RemoteAddr)
|
||||||
return
|
http.Error(w, err.Error(), http.StatusForbidden)
|
||||||
}
|
} else {
|
||||||
if !grantAccess {
|
log.Warningf("api: authenticator failed: %s", err)
|
||||||
log.Warningf("api: denying api access to %s", r.RemoteAddr)
|
http.Error(w, "Internal server error during authentication.", http.StatusInternalServerError)
|
||||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue