github.com/pavlo67/common@v0.5.3/common/auth/auth_server_http/middleware.go (about)

     1  package auth_server_http
     2  
     3  import (
     4  	"net/http"
     5  	"regexp"
     6  
     7  	"github.com/pavlo67/common/common/auth"
     8  	"github.com/pavlo67/common/common/errors"
     9  	"github.com/pavlo67/common/common/server_http"
    10  )
    11  
    12  var _ server_http.OnRequestMiddleware = &onRequestMiddleware{}
    13  
    14  func OnRequestMiddleware(authJWTOp auth.Operator) (server_http.OnRequestMiddleware, error) {
    15  	if authJWTOp == nil {
    16  		return nil, errors.New("no authJWTOp")
    17  	}
    18  
    19  	return &onRequestMiddleware{
    20  		authJWTOp: authJWTOp,
    21  	}, nil
    22  }
    23  
    24  type onRequestMiddleware struct {
    25  	authJWTOp auth.Operator
    26  }
    27  
    28  var reBearer = regexp.MustCompile(`^\s*Bearer(\s|%[fF]20)*`)
    29  
    30  const onOptions = "on onRequestMiddleware.Identity()"
    31  
    32  func (orm *onRequestMiddleware) Identity(r *http.Request) (*auth.Identity, error) {
    33  	//if r == nil {
    34  	//	return nil, errors.New("no server_http.Request in RequestOptions(...)")
    35  	//}
    36  
    37  	if tokenJWT := r.Header.Get("Authorization"); tokenJWT != "" {
    38  		tokenJWT = reBearer.ReplaceAllString(tokenJWT, "")
    39  		actor, err := orm.authJWTOp.Authenticate(auth.Creds{auth.CredsJWT: tokenJWT})
    40  		if err != nil {
    41  			return nil, errors.CommonError(err, onOptions)
    42  		}
    43  		if actor != nil {
    44  			return actor.Identity, nil
    45  		}
    46  	}
    47  
    48  	return nil, nil
    49  }
    50  
    51  //// SIGNATURE CHECK
    52  //signature := r.Header.Get("Signature")
    53  //if signature != "" && r.URL != nil {
    54  //	publicKeyAddress := r.Header.Get("Public-Key-Address")
    55  //	numberToSignature := r.Header.Get("Number-To-Signature")
    56  //
    57  //	credsSignature := auth.Creds{
    58  //		Values: map[auth.CredsType]string{
    59  //			auth.CredsPublicKeyBase58:    publicKeyAddress,
    60  //			auth.CredsContentToSignature: r.URL.Path + "?" + r.URL.RawQuery,
    61  //			auth.CredsKeyToSignature:     numberToSignature,
    62  //			auth.CredsSignature:          signature,
    63  //		},
    64  //	}
    65  //
    66  //	user, errs = auth.GetIdentity(credsSignature, authOps, errs)
    67  //	// previous errs is added by auth.GetIdentity()
    68  //}
    69  //var errNoIdentityOpsMap = errors.New("no map[CredsType]identity.UserKey")