mirror of
https://github.com/0x1d/rcond.git
synced 2025-12-14 18:25:21 +01:00
feat: add API token authentication
This commit is contained in:
@@ -10,11 +10,12 @@ import (
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
router *mux.Router
|
||||
srv *http.Server
|
||||
router *mux.Router
|
||||
srv *http.Server
|
||||
apiToken string
|
||||
}
|
||||
|
||||
func NewServer(addr string) *Server {
|
||||
func NewServer(addr string, apiToken string) *Server {
|
||||
router := mux.NewRouter()
|
||||
|
||||
srv := &http.Server{
|
||||
@@ -25,8 +26,9 @@ func NewServer(addr string) *Server {
|
||||
}
|
||||
|
||||
return &Server{
|
||||
router: router,
|
||||
srv: srv,
|
||||
router: router,
|
||||
srv: srv,
|
||||
apiToken: apiToken,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,13 +40,24 @@ func (s *Server) Shutdown(ctx context.Context) error {
|
||||
return s.srv.Shutdown(ctx)
|
||||
}
|
||||
|
||||
func (s *Server) verifyToken(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token := r.Header.Get("X-API-Token")
|
||||
if token == "" || token != s.apiToken {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) RegisterRoutes() {
|
||||
s.router.HandleFunc("/health", s.healthHandler).Methods(http.MethodGet)
|
||||
s.router.HandleFunc("/network/up", HandleNetworkUp).Methods(http.MethodPost)
|
||||
s.router.HandleFunc("/network/down", HandleNetworkDown).Methods(http.MethodPost)
|
||||
s.router.HandleFunc("/network/remove", HandleNetworkRemove).Methods(http.MethodPost)
|
||||
s.router.HandleFunc("/hostname", HandleGetHostname).Methods(http.MethodGet)
|
||||
s.router.HandleFunc("/hostname", HandleSetHostname).Methods(http.MethodPost)
|
||||
s.router.HandleFunc("/network/up", s.verifyToken(HandleNetworkUp)).Methods(http.MethodPost)
|
||||
s.router.HandleFunc("/network/down", s.verifyToken(HandleNetworkDown)).Methods(http.MethodPost)
|
||||
s.router.HandleFunc("/network/remove", s.verifyToken(HandleNetworkRemove)).Methods(http.MethodPost)
|
||||
s.router.HandleFunc("/hostname", s.verifyToken(HandleGetHostname)).Methods(http.MethodGet)
|
||||
s.router.HandleFunc("/hostname", s.verifyToken(HandleSetHostname)).Methods(http.MethodPost)
|
||||
}
|
||||
|
||||
func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
Reference in New Issue
Block a user