diff --git a/api/authentication.go b/api/authentication.go index 79bb2fe..8e48d71 100644 --- a/api/authentication.go +++ b/api/authentication.go @@ -37,16 +37,19 @@ type Authenticator func(ctx context.Context, s *http.Server, r *http.Request) (e // SetAuthenticator sets an authenticator function for the API endpoint. If none is set, all requests will be permitted. func SetAuthenticator(fn Authenticator) error { + if module.Online() { + return ErrAuthenticationAlreadySet + } + authFnLock.Lock() defer authFnLock.Unlock() - if authFn == nil { - authFn = fn - module.NewTask("clean api auth tokens", cleanAuthTokens).Repeat(time.Minute) - return nil + if authFn != nil { + return ErrAuthenticationAlreadySet } - return ErrAuthenticationAlreadySet + authFn = fn + return nil } func authMiddleware(next http.Handler) http.Handler { diff --git a/api/main.go b/api/main.go index 9d015f2..63f3c76 100644 --- a/api/main.go +++ b/api/main.go @@ -3,6 +3,7 @@ package api import ( "context" "errors" + "time" "github.com/safing/portbase/modules" ) @@ -13,7 +14,7 @@ var ( // API Errors var ( - ErrAuthenticationAlreadySet = errors.New("the authentication function has already been set") + ErrAuthenticationAlreadySet = errors.New("the authentication function has already been set (or must be set earlier)") ) func init() { @@ -30,6 +31,14 @@ func prep() error { func start() error { logFlagOverrides() go Serve() + + // start api auth token cleaner + authFnLock.Lock() + defer authFnLock.Unlock() + if authFn == nil { + module.NewTask("clean api auth tokens", cleanAuthTokens).Repeat(time.Minute) + } + return nil }