storj/pkg/auth/apikey.go
Maximillian von Briesen 5014a785a0
Node selection 0/4: Update statdb auth/functionality (#698)
* remove api key from statdb server reqs; add statdb UpdateUptime and UpdateAuditSuccess to server

* update api key authentication in statdb server

* add todos for future statdb updates

* add UpdateUptime and UpdateAuditSuccess to statdb server

* fix apikey stuff in config.go and statdb_test.go

* fix tests

* update sdbclient.NewClient call in audit package

* fix UpdateUptime and UpdateAuditSuccess in sdbclient

* set api key from statdb/config.go

* change package for statdb tests

* linter fixes

* remove todo comments

* fix sdbclient err checking

* move validate auth functionality to auth package

* update description for statdb api key

* remove import
2018-11-26 12:08:29 -05:00

42 lines
1.0 KiB
Go

// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package auth
import (
"context"
"crypto/subtle"
)
// The key type is unexported to prevent collisions with context keys defined in
// other packages.
type key int
// apiKey is the context key for the user API Key
const apiKey key = 0
// WithAPIKey creates context with api key
func WithAPIKey(ctx context.Context, key []byte) context.Context {
return context.WithValue(ctx, apiKey, key)
}
// GetAPIKey returns api key from context is exists
func GetAPIKey(ctx context.Context) ([]byte, bool) {
key, ok := ctx.Value(apiKey).([]byte)
return key, ok
}
// ValidateAPIKey compares the context api key with the key passed in as an argument
func ValidateAPIKey(ctx context.Context, actualKey []byte) error {
expectedKey, ok := GetAPIKey(ctx)
if !ok {
return Error.New("Could not get api key from context")
}
matches := (1 == subtle.ConstantTimeCompare(actualKey, expectedKey))
if !matches {
return Error.New("Invalid API credential")
}
return nil
}