-
Notifications
You must be signed in to change notification settings - Fork 96
/
openauth.go
86 lines (71 loc) · 2.41 KB
/
openauth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package middleware
import (
"bytes"
"encoding/gob"
"fmt"
"io/ioutil"
"math"
"time"
"github.com/douyu/juno/internal/pkg/packages/contrib/output"
"github.com/douyu/juno/internal/pkg/service/openauth"
"github.com/douyu/juno/pkg/model/db"
"github.com/douyu/juno/pkg/util"
"github.com/labstack/echo/v4"
)
type OpenAuthCommonPayload struct {
AppID string `json:"app_id" query:"app_id" validate:"required"`
Timestamp int64 `json:"timestamp" query:"timestamp" validate:"required"`
NonceStr string `json:"nonce_str" query:"nonce_str" validate:"required"`
Sign string `json:"sign" query:"sign" validate:"required"`
}
func OpenAuth(next echo.HandlerFunc) echo.HandlerFunc {
gob.Register(db.AccessToken{})
return func(c echo.Context) error {
bodyContent, _ := ioutil.ReadAll(c.Request().Body)
c.Request().Body = ioutil.NopCloser(bytes.NewReader(bodyContent))
authParam := OpenAuthCommonPayload{}
b := echo.DefaultBinder{}
err := b.BindQueryParams(c, &authParam)
if err != nil {
return output.JSON(c, output.MsgOpenAuthFailed, err.Error(), nil)
}
err = b.Bind(&authParam, c)
if err != nil {
return output.JSON(c, output.MsgOpenAuthFailed, err.Error(), nil)
}
err = c.Validate(&authParam)
if err != nil {
return output.JSON(c, output.MsgOpenAuthFailed, err.Error(), nil)
}
// 写回Body
c.Request().Body = ioutil.NopCloser(bytes.NewReader(bodyContent))
token, err := openauth.OpenAuthService.GetAccessTokenByAppID(authParam.AppID)
if err != nil {
return output.JSON(c, output.MsgOpenAuthFailed, err.Error(), nil)
}
err = checkOpenAuthPayload(authParam.AppID, authParam.NonceStr, token.Secret, authParam.Sign, authParam.Timestamp)
if err != nil {
return output.JSON(c, output.MsgOpenAuthFailed, err.Error(), nil)
}
c.Set("OpenAuthAccessToken", token)
return next(c)
}
}
func checkOpenAuthPayload(appId, nonceStr, secret, sign string, timestamp int64) (err error) {
if len(nonceStr) != 16 {
return fmt.Errorf("nonceStr 长度无效")
}
if math.Abs(float64(time.Now().Unix()-timestamp)) > 10 {
return fmt.Errorf("token expired")
}
realSign := openAuthSign(appId, nonceStr, secret, timestamp)
if realSign != sign {
return fmt.Errorf("签名无效")
}
return
}
// 计算签名
func openAuthSign(appId, nonceStr, secret string, timestamp int64) (sign string) {
plainText := fmt.Sprintf("%s%s%s%d", appId, nonceStr, secret, timestamp)
return util.Md5Str(plainText)
}