feat: 添加鉴权组件

This commit is contained in:
lixiangwuxian 2024-10-20 01:24:45 +08:00
parent 0efdd71c8a
commit b1fa836304
4 changed files with 72 additions and 2 deletions

View File

@ -1,5 +1,37 @@
package auth
func isRootUser(qqID string) bool {
return false
import (
"git.lxtend.com/qqbot/handler"
"git.lxtend.com/qqbot/model"
"git.lxtend.com/qqbot/sqlite3"
)
func init() {
authTableCreateSQL := `
CREATE TABLE IF NOT EXISTS auth (
id INTEGER PRIMARY KEY AUTOINCREMENT,
qqid TEXT UNIQUE,
role INTEGER
);
`
sqlite3.TryCreateTable(authTableCreateSQL)
}
func HasPermission(qqID int64, level int) bool {
auth, err := getAuth(qqID)
if err != nil {
return false
}
return auth.Role <= level
}
func TryExecHandler(msg model.Message, level int, handler handler.Handler) (reply model.Reply) {
if HasPermission(msg.UserId, level) {
return handler(msg)
}
return model.Reply{
ReplyMsg: "权限验证失败",
ReferOriginMsg: true,
FromMsg: msg,
}
}

6
auth/model.go Normal file
View File

@ -0,0 +1,6 @@
package auth
type Auth struct {
Qqid string `json:"qqid" db:"qqid"`
Role int `json:"role" db:"role"`
}

24
auth/service.go Normal file
View File

@ -0,0 +1,24 @@
package auth
import (
"database/sql"
"git.lxtend.com/qqbot/constants"
"git.lxtend.com/qqbot/sqlite3"
)
func getAuth(qqID int64) (auth Auth, err error) {
tx, err := sqlite3.GetTran()
if err != nil {
return Auth{}, err
}
defer tx.Rollback()
err = tx.Get(&auth, "SELECT * FROM auth WHERE qqid = ?", qqID)
if err == sql.ErrNoRows {
_, err = tx.Exec("INSERT INTO auth(qqid, role) VALUES(?, ?)", qqID, constants.LEVEL_USER)
}
if err != nil {
return Auth{}, err
}
return auth, nil
}

8
constants/auth.go Normal file
View File

@ -0,0 +1,8 @@
package constants
const (
LEVEL_ROOT = 0
LEVEL_ADMIN = 10
LEVEL_USER = 20 //default
LEVEL_BANNED = 100
)