gitee.com/larksuite/oapi-sdk-go/v3@v3.0.3/event/event.go (about)

     1  /*
     2   * MIT License
     3   *
     4   * Copyright (c) 2022 Lark Technologies Pte. Ltd.
     5   *
     6   * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
     7   *
     8   * The above copyright notice and this permission notice, shall be included in all copies or substantial portions of the Software.
     9   *
    10   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    11   */
    12  
    13  package larkevent
    14  
    15  import (
    16  	"context"
    17  	"crypto/aes"
    18  	"crypto/cipher"
    19  	"crypto/sha256"
    20  	"encoding/base64"
    21  	"fmt"
    22  	"strings"
    23  
    24  	"gitee.com/larksuite/oapi-sdk-go/v3/core"
    25  )
    26  
    27  type EventHandler interface {
    28  	Event() interface{}                        // 用于返回事件消息结构体(即承载回调消息内容的结构体)
    29  	Handle(context.Context, interface{}) error // 用于处理事件
    30  }
    31  
    32  type EventHandlerModel interface {
    33  	RawReq(req *EventReq)
    34  }
    35  
    36  type IReqHandler interface {
    37  	Handle(ctx context.Context, req *EventReq) *EventResp
    38  	Logger() larkcore.Logger
    39  }
    40  
    41  type DecryptErr struct {
    42  	Message string
    43  }
    44  
    45  func newDecryptErr(message string) *DecryptErr {
    46  	return &DecryptErr{Message: message}
    47  }
    48  func (e DecryptErr) Error() string {
    49  	return e.Message
    50  }
    51  
    52  // eventDecrypt returns decrypt bytes
    53  func EventDecrypt(encrypt string, secret string) ([]byte, error) {
    54  	buf, err := base64.StdEncoding.DecodeString(encrypt)
    55  	if err != nil {
    56  		return nil, newDecryptErr(fmt.Sprintf("base64 decode error: %v", err))
    57  	}
    58  	if len(buf) < aes.BlockSize {
    59  		return nil, newDecryptErr("cipher too short")
    60  	}
    61  	key := sha256.Sum256([]byte(secret))
    62  	block, err := aes.NewCipher(key[:sha256.Size])
    63  	if err != nil {
    64  		return nil, newDecryptErr(fmt.Sprintf("AES new cipher error %v", err))
    65  	}
    66  	iv := buf[:aes.BlockSize]
    67  	buf = buf[aes.BlockSize:]
    68  	// CBC mode always works in whole blocks.
    69  	if len(buf)%aes.BlockSize != 0 {
    70  		return nil, newDecryptErr("ciphertext is not a multiple of the block size")
    71  	}
    72  	mode := cipher.NewCBCDecrypter(block, iv)
    73  	mode.CryptBlocks(buf, buf)
    74  	n := strings.Index(string(buf), "{")
    75  	if n == -1 {
    76  		n = 0
    77  	}
    78  	m := strings.LastIndex(string(buf), "}")
    79  	if m == -1 {
    80  		m = len(buf) - 1
    81  	}
    82  	return buf[n : m+1], nil
    83  }
    84  
    85  func Signature(timestamp string, nonce string, eventEncryptKey string, body string) string {
    86  	var b strings.Builder
    87  	b.WriteString(timestamp)
    88  	b.WriteString(nonce)
    89  	b.WriteString(eventEncryptKey)
    90  	b.WriteString(body)
    91  	bs := []byte(b.String())
    92  	h := sha256.New()
    93  	_, _ = h.Write(bs)
    94  	bs = h.Sum(nil)
    95  	return fmt.Sprintf("%x", bs)
    96  }
    97  
    98  type OptionFunc func(config *larkcore.Config)
    99  
   100  func WithLogger(logger larkcore.Logger) OptionFunc {
   101  	return func(config *larkcore.Config) {
   102  		config.Logger = logger
   103  	}
   104  }
   105  
   106  func WithLogLevel(logLevel larkcore.LogLevel) OptionFunc {
   107  	return func(config *larkcore.Config) {
   108  		config.LogLevel = logLevel
   109  	}
   110  }