2019-01-24 16:26:36 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
2018-11-15 12:00:08 +00:00
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
2019-01-15 13:03:24 +00:00
|
|
|
package console
|
2018-11-14 10:50:15 +00:00
|
|
|
|
|
|
|
import (
|
2018-11-27 14:20:58 +00:00
|
|
|
"context"
|
2018-11-14 10:50:15 +00:00
|
|
|
"encoding/base64"
|
|
|
|
|
2018-11-27 14:20:58 +00:00
|
|
|
"github.com/zeebo/errs"
|
|
|
|
|
2019-01-15 13:03:24 +00:00
|
|
|
"storj.io/storj/satellite/console/consoleauth"
|
2018-11-14 10:50:15 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
//TODO: change to JWT or Macaroon based auth
|
|
|
|
|
|
|
|
// Signer creates signature for provided data
|
|
|
|
type Signer interface {
|
|
|
|
Sign(data []byte) ([]byte, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// signToken signs token with given signer
|
2019-01-15 13:03:24 +00:00
|
|
|
func signToken(token *consoleauth.Token, signer Signer) error {
|
2018-11-14 10:50:15 +00:00
|
|
|
encoded := base64.URLEncoding.EncodeToString(token.Payload)
|
|
|
|
|
|
|
|
signature, err := signer.Sign([]byte(encoded))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
token.Signature = signature
|
|
|
|
return nil
|
|
|
|
}
|
2018-11-27 14:20:58 +00:00
|
|
|
|
|
|
|
// key is a context value key type
|
|
|
|
type key int
|
|
|
|
|
|
|
|
// authKey is context key for Authorization
|
|
|
|
const authKey key = 0
|
|
|
|
|
|
|
|
// ErrUnauthorized is error class for authorization related errors
|
|
|
|
var ErrUnauthorized = errs.Class("unauthorized error")
|
|
|
|
|
|
|
|
// Authorization contains auth info of authorized User
|
|
|
|
type Authorization struct {
|
|
|
|
User User
|
2019-01-15 13:03:24 +00:00
|
|
|
Claims consoleauth.Claims
|
2018-11-27 14:20:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// WithAuth creates new context with Authorization
|
|
|
|
func WithAuth(ctx context.Context, auth Authorization) context.Context {
|
|
|
|
return context.WithValue(ctx, authKey, auth)
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithAuthFailure creates new context with authorization failure
|
|
|
|
func WithAuthFailure(ctx context.Context, err error) context.Context {
|
|
|
|
return context.WithValue(ctx, authKey, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetAuth gets Authorization from context
|
|
|
|
func GetAuth(ctx context.Context) (Authorization, error) {
|
|
|
|
value := ctx.Value(authKey)
|
|
|
|
|
|
|
|
if auth, ok := value.(Authorization); ok {
|
|
|
|
return auth, nil
|
|
|
|
}
|
|
|
|
|
2019-09-04 16:02:39 +01:00
|
|
|
if err, ok := value.(error); ok {
|
|
|
|
return Authorization{}, err
|
2018-11-27 14:20:58 +00:00
|
|
|
}
|
|
|
|
|
2019-04-10 01:15:12 +01:00
|
|
|
return Authorization{}, errs.New(unauthorizedErrMsg)
|
2018-11-27 14:20:58 +00:00
|
|
|
}
|