mtfosbot/router/line/line.go

109 lines
2.0 KiB
Go
Raw Permalink Normal View History

2018-09-02 01:15:35 +00:00
package line
2018-09-13 10:18:59 +00:00
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"io/ioutil"
2019-06-25 09:02:03 +00:00
"git.trj.tw/golang/mtfosbot/model"
2018-09-13 10:18:59 +00:00
"git.trj.tw/golang/mtfosbot/module/context"
2019-06-25 09:02:03 +00:00
linemsg "git.trj.tw/golang/mtfosbot/module/line-message"
2018-09-13 10:18:59 +00:00
lineobj "git.trj.tw/golang/mtfosbot/module/line-message/line-object"
)
// GetRawBody - line webhook body get
func GetRawBody(c *context.Context) {
byteBody, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.DataFormat("body read fail")
return
}
c.Set("rawbody", byteBody)
c.Next()
}
// VerifyLine - middleware
func VerifyLine(c *context.Context) {
rawbody, ok := c.Get("rawbody")
if !ok {
c.DataFormat("body read fail")
return
}
var raw []byte
if raw, ok = rawbody.([]byte); !ok {
c.DataFormat("body type error")
return
}
sign := c.GetHeader("X-Line-Signature")
if len(sign) == 0 {
c.Next()
return
}
2019-06-25 09:02:03 +00:00
botid, ok := c.GetQuery("id")
if !ok || len(botid) == 0 {
c.CustomRes(403, map[string]string{
"message": "no bot data",
})
}
2018-09-13 10:18:59 +00:00
2019-06-25 09:02:03 +00:00
bot, err := model.GetBotInfo(botid)
if err != nil {
c.ServerError(nil)
return
}
hash := hmac.New(sha256.New, []byte(bot.Secret))
_, err = hash.Write(raw)
2018-09-13 10:18:59 +00:00
if err != nil {
c.ServerError(nil)
return
}
hashSign := base64.StdEncoding.EncodeToString(hash.Sum(nil))
if hashSign != sign {
c.CustomRes(403, map[string]string{
"message": "sign verify fail",
})
return
}
c.Next()
}
2018-09-02 01:15:35 +00:00
// GetLineMessage -
func GetLineMessage(c *context.Context) {
2018-09-13 10:18:59 +00:00
rawbody, ok := c.Get("rawbody")
if !ok {
c.DataFormat("body read fail")
}
var raw []byte
if raw, ok = rawbody.([]byte); !ok {
c.DataFormat("body type error")
}
2019-06-25 09:02:03 +00:00
botid, ok := c.GetQuery("id")
if !ok || len(botid) == 0 {
c.CustomRes(403, map[string]string{
"message": "no bot data",
})
}
2018-09-13 10:18:59 +00:00
events := struct {
Events []*lineobj.EventObject `json:"events"`
}{}
err := json.Unmarshal(raw, &events)
if err != nil {
c.ServerError(nil)
return
}
if len(events.Events) > 0 {
for _, v := range events.Events {
2019-06-25 09:02:03 +00:00
go linemsg.MessageEvent(botid, v)
2018-09-13 10:18:59 +00:00
}
}
2018-09-02 01:15:35 +00:00
2018-09-13 10:18:59 +00:00
c.Success(nil)
2018-09-02 01:15:35 +00:00
}