swap out context access for account (#1589)

This commit is contained in:
Asim Aslam 2020-04-28 17:35:18 +01:00 committed by GitHub
parent 9bb1904a38
commit f908110fb6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 32 deletions

View File

@ -3,11 +3,8 @@ package auth
import (
"context"
"encoding/json"
"errors"
"time"
"github.com/micro/go-micro/v2/metadata"
)
var (
@ -90,8 +87,6 @@ type Token struct {
const (
// DefaultNamespace used for auth
DefaultNamespace = "go.micro"
// MetadataKey is the key used when storing the account in metadata
MetadataKey = "auth-account"
// TokenCookieName is the name of the cookie which stores the auth token
TokenCookieName = "micro-token"
// SecretCookieName is the name of the cookie which stores the auth secret
@ -100,34 +95,18 @@ const (
BearerScheme = "Bearer "
)
type accountKey struct{}
// AccountFromContext gets the account from the context, which
// is set by the auth wrapper at the start of a call. If the account
// is not set, a nil account will be returned. The error is only returned
// when there was a problem retrieving an account
func AccountFromContext(ctx context.Context) (*Account, error) {
str, ok := metadata.Get(ctx, MetadataKey)
// there was no account set
if !ok {
return nil, nil
}
var acc *Account
// metadata is stored as a string, so unmarshal to an account
if err := json.Unmarshal([]byte(str), &acc); err != nil {
return nil, err
}
return acc, nil
func AccountFromContext(ctx context.Context) (*Account, bool) {
acc, ok := ctx.Value(accountKey{}).(*Account)
return acc, ok
}
// ContextWithAccount sets the account in the context
func ContextWithAccount(ctx context.Context, account *Account) (context.Context, error) {
// metadata is stored as a string, so marshal to bytes
bytes, err := json.Marshal(account)
if err != nil {
return ctx, err
}
// generate a new context with the MetadataKey set
return metadata.Set(ctx, MetadataKey, string(bytes)), nil
func ContextWithAccount(ctx context.Context, account *Account) context.Context {
return context.WithValue(ctx, accountKey{}, account)
}

View File

@ -178,10 +178,7 @@ func AuthHandler(fn func() auth.Auth) server.HandlerWrapper {
}
// There is an account, set it in the context
ctx, err = auth.ContextWithAccount(ctx, account)
if err != nil {
return err
}
ctx = auth.ContextWithAccount(ctx, account)
// The user is authorised, allow the call
return h(ctx, req, rsp)