/
auth.go
66 lines (55 loc) · 1.35 KB
/
auth.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
package broker
import (
"bytes"
mqtt "github.com/mochi-mqtt/server/v2"
"github.com/mochi-mqtt/server/v2/packets"
"github.com/zgwit/iot-master/v4/db"
"github.com/zgwit/iot-master/v4/log"
"github.com/zgwit/iot-master/v4/pkg/vconn"
)
type Auth struct {
mqtt.HookBase
}
// ID returns the ID of the hook.
func (h *Auth) ID() string {
return "gateway"
}
// Provides indicates which hook methods this hook provides.
func (h *Auth) Provides(b byte) bool {
return bytes.Contains([]byte{
mqtt.OnConnectAuthenticate,
mqtt.OnACLCheck,
}, []byte{b})
}
// OnConnectAuthenticate returns true/allowed for all requests.
func (h *Auth) OnConnectAuthenticate(cl *mqtt.Client, pk packets.Packet) bool {
if cl.Net.Inline {
return true
}
//内部虚拟连接
if _, ok := cl.Net.Conn.(*vconn.VConn); ok {
return true
}
//Websocket连接
if _, ok := cl.Net.Conn.(*wsConn); ok {
return true
}
//根据网关ID,查密码
var gw Gateway
has, err := db.Engine.ID(cl.ID).Get(&gw)
if err != nil {
log.Error(err)
return false
}
if !has {
return false
}
if gw.Username == "" || gw.Password == "" {
return true
}
return gw.Username == string(pk.Connect.Username) && gw.Password == string(pk.Connect.Password)
}
// OnACLCheck returns true/allowed for all checks.
func (h *Auth) OnACLCheck(cl *mqtt.Client, topic string, write bool) bool {
return true
}