Skip to content

Commit

Permalink
feat(server): add apikey auth method
Browse files Browse the repository at this point in the history
  • Loading branch information
qdm12 committed Sep 4, 2024
1 parent 7c177f1 commit abe5934
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
31 changes: 31 additions & 0 deletions internal/server/middlewares/auth/apikey.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package auth

import "net/http"

type apiKeyMethod struct {
apiKey string
}

func newAPIKeyMethod(apiKey string) *apiKeyMethod {
return &apiKeyMethod{
apiKey: apiKey,
}
}

// equal returns true if another auth checker is equal.
// This is used to deduplicate checkers for a particular route.
func (a *apiKeyMethod) equal(other authorizationChecker) bool {
otherTokenMethod, ok := other.(*apiKeyMethod)
if !ok {
return false
}
return a.apiKey == otherTokenMethod.apiKey
}

func (a *apiKeyMethod) isAuthorized(_ http.ResponseWriter, request *http.Request) bool {
xAPIKey := request.Header.Get("X-API-Key")
if xAPIKey == "" {
xAPIKey = request.URL.Query().Get("api_key")
}
return xAPIKey == a.apiKey
}
2 changes: 2 additions & 0 deletions internal/server/middlewares/auth/lookup.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ func settingsToLookupMap(settings Settings) (routeToRoles map[Route][]internalRo
switch auth.Method {
case MethodNone:
authNameToChecker[auth.Name] = newNoneMethod()
case MethodAPIKey:
authNameToChecker[auth.Name] = newAPIKeyMethod(auth.APIKey)
default:
return nil, fmt.Errorf("%w: %s", ErrMethodNotSupported, auth.Name)
}
Expand Down
7 changes: 5 additions & 2 deletions internal/server/middlewares/auth/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ func (s Settings) ToLinesNode() (node *gotree.Node) {
}

const (
MethodNone = "none"
MethodNone = "none"
MethodAPIKey = "apikey"
)

// Auth contains the authentication method name and fields
Expand All @@ -130,6 +131,8 @@ type Auth struct {
Name string
// Method is the authentication method to use.
Method string
// APIKey is the API key to use for the API key authentication method.
APIKey string
}

func (a Auth) validate() (err error) {
Expand All @@ -145,7 +148,7 @@ var (
)

func validateAuthMethod(method string) (err error) {
err = validate.IsOneOf(method, MethodNone)
err = validate.IsOneOf(method, MethodNone, MethodAPIKey)
if err != nil {
return fmt.Errorf("%w: %s", ErrMethodNotSupported, method)
}
Expand Down

0 comments on commit abe5934

Please sign in to comment.