local-server/cmd/dkl-local-server/ws-auth.go
Mikaël Cluseau 4acdf88785 misc fixes
2023-02-13 17:31:37 +01:00

46 lines
984 B
Go

package main
import (
"strings"
restful "github.com/emicklei/go-restful"
)
func adminAuth(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
tokenAuth(req, resp, chain, *adminToken)
}
func hostsAuth(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
tokenAuth(req, resp, chain, *hostsToken, *adminToken)
}
func tokenAuth(req *restful.Request, resp *restful.Response, chain *restful.FilterChain, allowedTokens ...string) {
token := getToken(req)
for _, allowedToken := range allowedTokens {
if allowedToken == "" || token == allowedToken {
chain.ProcessFilter(req, resp)
return
}
}
wsError(resp, ErrUnauthorized)
return
}
func getToken(req *restful.Request) string {
const bearerPrefix = "Bearer "
token := req.HeaderParameter("Authorization")
if token == "" {
return req.QueryParameter("token")
}
if !strings.HasPrefix(token, bearerPrefix) {
return token
}
return token[len(bearerPrefix):]
}