gitee.com/h79/goutils@v1.22.10/api/bind.go (about)

     1  package api
     2  
     3  import (
     4  	"gitee.com/h79/goutils/auth/token"
     5  	"gitee.com/h79/goutils/common/result"
     6  	"gitee.com/h79/goutils/common/stringutil"
     7  	"strings"
     8  )
     9  
    10  const (
    11  	Head  = "HEADER"
    12  	Token = "TOKEN"
    13  	Uid   = "UID"
    14  )
    15  
    16  type HeadOption func(ctx Context, header *Header)
    17  
    18  func BindHead(ctx Context, option HeadOption) {
    19  	header := NewHeader(ReqHead{})
    20  	header.ReadFrom(ctx)
    21  	if option != nil {
    22  		option(ctx, header)
    23  	}
    24  	header.ClientIP = ctx.HttpContext().ClientIP()
    25  	ctx.CacheContext().Set(Head, header)
    26  }
    27  
    28  func WithHeadOption(ctx Context, header *Header) {
    29  	if header.Version == "" {
    30  		header.Version = ctx.HttpContext().Query(CVersion)
    31  	}
    32  	if header.Source == "" {
    33  		header.Source = ctx.HttpContext().Query(CSource)
    34  	}
    35  	if header.SeqId == "" {
    36  		header.SeqId = ctx.HttpContext().Query(CSeqId)
    37  	}
    38  	if header.ReqAt == 0 {
    39  		header.ReqAt = stringutil.StringToInt64(ctx.HttpContext().Query(CTimeAt))
    40  	}
    41  	if header.App.AppId == "" {
    42  		header.App.AppId = ctx.HttpContext().Query(CAppId)
    43  	}
    44  	if header.App.Terminal == "" {
    45  		header.App.Terminal = ctx.HttpContext().Query(CTerminal)
    46  	}
    47  	if header.App.Version == "" {
    48  		header.App.Version = header.Version
    49  	}
    50  	if header.App.Source == "" {
    51  		header.App.Source = header.Source
    52  	}
    53  }
    54  
    55  const kToken = "token"
    56  
    57  func GetTokenSource(ctx Context) token.Source {
    58  	base := GetBase(ctx)
    59  	return token.Source{AppId: base.App.AppId, Source: base.App.Source}
    60  }
    61  
    62  func TokenReq(ctx Context) (string, error) {
    63  	return GetToken(ctx, CToken)
    64  }
    65  
    66  func GetToken(ctx Context, keys ...string) (string, error) {
    67  	var tok = ""
    68  	var header = ctx.HeaderContext()
    69  	for i := range keys {
    70  		tok = header.Get(keys[i])
    71  		if len(tok) > 6 {
    72  			if strings.ToUpper(tok[0:7]) == "BEARER " {
    73  				return tok[7:], nil
    74  			}
    75  			return tok, nil
    76  		}
    77  	}
    78  	tok = header.Get(kToken)
    79  	if len(tok) > 0 {
    80  		return tok, nil
    81  	}
    82  	tok = ctx.HttpContext().Query(kToken)
    83  	if len(tok) > 0 {
    84  		return tok, nil
    85  	}
    86  	return "", result.RErrAuth
    87  }
    88  
    89  func Bearer(tok string) string {
    90  	if len(tok) <= 0 {
    91  		return ""
    92  	}
    93  	if strings.ToUpper(tok[0:7]) == "BEARER " {
    94  		return tok
    95  	}
    96  	return "Bearer " + tok
    97  }