hashedSecret := make([]byte, tokenSize)
sha3pool.Sum256(hashedSecret, secret)
- created := time.Now()
token := &Token{
ID: id,
Token: fmt.Sprintf("%s:%x", id, hashedSecret),
Type: typ,
- Created: created,
+ Created: time.Now(),
}
value, err := json.Marshal(token)
return nil, err
}
cs.DB.Set(key, value)
- hexsec := fmt.Sprintf("%s:%x", id, secret)
- return &hexsec, nil
+
+ return &token.Token, nil
}
// Check returns whether or not an id-secret pair is a valid access token.
-func (cs *CredentialStore) Check(ctx context.Context, id string, secret []byte) (bool, error) {
+func (cs *CredentialStore) Check(ctx context.Context, id string, secret string) (bool, error) {
if !validIDRegexp.MatchString(id) {
return false, errors.WithDetailf(ErrBadID, "invalid id %q", id)
}
- var toHash [tokenSize]byte
- var hashed [tokenSize]byte
- copy(toHash[:], secret)
- sha3pool.Sum256(hashed[:], toHash[:])
- inToken := fmt.Sprintf("%s:%x", id, hashed[:])
-
var value []byte
token := &Token{}
- key := []byte(id)
- if value = cs.DB.Get(key); value == nil {
+ if value = cs.DB.Get([]byte(id)); value == nil {
return false, errors.WithDetailf(ErrNoMatchID, "check id %q nonexisting", id)
}
if err := json.Unmarshal(value, token); err != nil {
return false, err
}
- if strings.Compare(token.Token, inToken) == 0 {
+ if strings.Compare(strings.Split(token.Token, ":")[1], secret) == 0 {
return true, nil
}
import (
"context"
- "encoding/hex"
"os"
"strings"
"testing"
token := mustCreateToken(ctx, t, cs, "x", "client")
tokenParts := strings.Split(*token, ":")
- tokenID := tokenParts[0]
- tokenSecret, err := hex.DecodeString(tokenParts[1])
- if err != nil {
- t.Fatal("bad token secret")
- }
- valid, err := cs.Check(ctx, tokenID, tokenSecret)
+ valid, err := cs.Check(ctx, tokenParts[0], tokenParts[1])
if err != nil {
t.Fatal(err)
}
t.Fatal("expected token and secret to be valid")
}
- valid, err = cs.Check(ctx, "x", []byte("badsecret"))
+ valid, err = cs.Check(ctx, "x", "badsecret")
if err != nil {
t.Fatal(err)
}
return user, a.cachedTokenAuthnCheck(req.Context(), user, pw)
}
-func (a *API) tokenAuthnCheck(ctx context.Context, user, pw string) (bool, error) {
- pwBytes, err := hex.DecodeString(pw)
- if err != nil {
- return false, nil
- }
- return a.tokens.Check(ctx, user, pwBytes)
-}
-
func (a *API) cachedTokenAuthnCheck(ctx context.Context, user, pw string) error {
a.tokenMu.Lock()
- res, ok := a.tokenMap[user+pw]
+ res, ok := a.tokenMap[user + pw]
a.tokenMu.Unlock()
if !ok || time.Now().After(res.lastLookup.Add(tokenExpiry)) {
- valid, err := a.tokenAuthnCheck(ctx, user, pw)
+ valid, err := a.tokens.Check(ctx, user, pw)
if err != nil {
return errors.Wrap(err)
}
res = tokenResult{valid: valid, lastLookup: time.Now()}
a.tokenMu.Lock()
- a.tokenMap[user+pw] = res
+ a.tokenMap[user + pw] = res
a.tokenMu.Unlock()
}
if !res.valid {