Skip to content
This repository has been archived by the owner on Nov 8, 2023. It is now read-only.

Commit

Permalink
Merge branch 'ThingsPanel:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
November-12 authored Sep 13, 2023
2 parents 9e9a4e9 + e6b955d commit ef65d87
Show file tree
Hide file tree
Showing 7 changed files with 100 additions and 81 deletions.
54 changes: 18 additions & 36 deletions controllers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ import (
context2 "github.com/beego/beego/v2/server/web/context"

jwt "ThingsPanel-Go/utils"

gjwt "github.com/golang-jwt/jwt"
)

type AuthController struct {
Expand Down Expand Up @@ -82,11 +80,11 @@ func (c *AuthController) Login() {
return
}
// 存入redis
redis.SetStr(token, "1", time.Hour)
redis.SetStr(token, "1", 24*time.Hour)
d := TokenData{
AccessToken: token,
TokenType: "Bearer",
ExpiresIn: int(time.Hour.Seconds()),
ExpiresIn: int(24 * time.Hour.Seconds()),
}
response.SuccessWithDetailed(200, "登录成功", d, map[string]string{}, (*context2.Context)(c.Ctx))
}
Expand All @@ -112,14 +110,15 @@ func (t *AuthController) Logout() {
}

// 刷新token
func (this *AuthController) Refresh() {
authorization := this.Ctx.Request.Header["Authorization"][0]
func (c *AuthController) ChangeToken() {
authorization := c.Ctx.Request.Header["Authorization"][0]
userToken := authorization[7:]
_, err := jwt.ParseCliamsToken(userToken)
if err != nil {
response.SuccessWithMessage(400, "token异常", (*context2.Context)(this.Ctx))
response.SuccessWithMessage(400, "token异常", (*context2.Context)(c.Ctx))
return
}
// 生成令牌
// 更新token时间
redis.SetStr(userToken, "1", 3000*time.Second)
d := TokenData{
Expand All @@ -128,54 +127,37 @@ func (this *AuthController) Refresh() {
ExpiresIn: 3600,
}
// cache.Bm.Put(c.TODO(), token, 1, 3000*time.Second)
response.SuccessWithDetailed(200, "刷新token成功", d, map[string]string{}, (*context2.Context)(this.Ctx))
response.SuccessWithDetailed(200, "刷新token成功", d, map[string]string{}, (*context2.Context)(c.Ctx))
}

// 刷新token
func (this *AuthController) ChangeToken() {
authorization := this.Ctx.Request.Header["Authorization"][0]
func (c *AuthController) Refresh() {
authorization := c.Ctx.Request.Header["Authorization"][0]
userToken := authorization[7:]
user, err := jwt.ParseCliamsToken(userToken)
jwtuser, err := jwt.ParseCliamsToken(userToken)
if err != nil {
response.SuccessWithMessage(400, "token异常", (*context2.Context)(this.Ctx))
response.SuccessWithMessage(400, "token异常", (*context2.Context)(c.Ctx))
return
}
// 生成jwt
if redis.GetStr(userToken) == "1" {
redis.DelKey(userToken)
}
// s, _ := cache.Bm.IsExist(c.TODO(), userToken)
// if s {
// cache.Bm.Delete(c.TODO(), userToken)
// }
var UserService services.UserService
_, i := UserService.GetUserById(user.ID)
user, i := UserService.GetUserById(jwtuser.ID)
if i == 0 {
response.SuccessWithMessage(400, "该账户不存在", (*context2.Context)(this.Ctx))
response.SuccessWithMessage(400, "该账户不存在", (*context2.Context)(c.Ctx))
return
}
// 生成jwt
tokenCliams := jwt.UserClaims{
ID: user.ID,
Name: user.Name,
CreateTime: time.Now(),
StandardClaims: gjwt.StandardClaims{
ExpiresAt: time.Now().Unix() + 3600,
},
}
token, err := jwt.MakeCliamsToken(tokenCliams)
token, err := jwt.GenerateToken(user)
if err != nil {
response.SuccessWithMessage(400, "jwt失败", (*context2.Context)(this.Ctx))
response.SuccessWithMessage(400, err.Error(), (*context2.Context)(c.Ctx))
return
}
d := TokenData{
AccessToken: token,
TokenType: "Bearer",
ExpiresIn: 3600,
ExpiresIn: int(24 * time.Hour.Seconds()),
}
redis.SetStr(token, "1", 3000*time.Second)
redis.SetStr(token, "24", time.Hour)
// cache.Bm.Put(c.TODO(), token, 1, 3000*time.Second)
response.SuccessWithDetailed(200, "刷新token成功", d, map[string]string{}, (*context2.Context)(this.Ctx))
response.SuccessWithDetailed(200, "刷新token成功", d, map[string]string{}, (*context2.Context)(c.Ctx))
}

// 个人信息
Expand Down
28 changes: 28 additions & 0 deletions controllers/kv.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,34 @@ func (KvController *KvController) HistoryData() {
response.SuccessWithDetailed(200, "success", trees, map[string]string{}, (*context2.Context)(KvController.Ctx))
}

// 删除指定属性历史数据
func (KvController *KvController) DeleteHistoryData() {
var TSKVService services.TSKVService
DeleteHistoryDataValidate := valid.DeleteHistoryDataValidate{}
err := json.Unmarshal(KvController.Ctx.Input.RequestBody, &DeleteHistoryDataValidate)
if err != nil {
fmt.Println("参数解析失败", err.Error())
}
v := validation.Validation{}
status, _ := v.Valid(DeleteHistoryDataValidate)
if !status {
for _, err := range v.Errors {
// 获取字段别称
alias := gvalid.GetAlias(DeleteHistoryDataValidate, err.Field)
message := strings.Replace(err.Message, err.Field, alias, 1)
response.SuccessWithMessage(1000, message, (*context2.Context)(KvController.Ctx))
break
}
return
}
isDelete, _ := TSKVService.DeleteHistoryData(DeleteHistoryDataValidate.DeviceId, DeleteHistoryDataValidate.Attribute)
if isDelete {
response.SuccessWithDetailed(200, "success", "", map[string]string{}, (*context2.Context)(KvController.Ctx))
}else {
response.SuccessWithMessage(400, "failed", (*context2.Context)(KvController.Ctx))
}
}

// 获取设备当前值
func (KvController *KvController) GetCurrentDataAndMap() {
CurrentKV := valid.CurrentKV{}
Expand Down
55 changes: 27 additions & 28 deletions initialize/casbin/casbin.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,50 +9,42 @@ import (
beego "github.com/beego/beego/v2/server/web"
"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v3"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)

var CasbinEnforcer *casbin.Enforcer

func init() {
log.Println("casbin启动...")

// 从配置文件中获取PostgreSQL数据库的配置信息
psqluser, err := beego.AppConfig.String("psqluser")
if err != nil {
log.Fatalf("Failed to get psqluser: %v", err)
}
checkErr(err, "Failed to get psqluser")

psqlpass, err := beego.AppConfig.String("psqlpass")
if err != nil {
log.Fatalf("Failed to get psqlpass: %v", err)
}
checkErr(err, "Failed to get psqlpass")

psqladdr := os.Getenv("TP_PG_IP")
if psqladdr == "" {
psqladdr, err = beego.AppConfig.String("psqladdr")
if err != nil {
log.Fatalf("Failed to get psqladdr: %v", err)
}
checkErr(err, "Failed to get psqladdr")
}

psqlports := os.Getenv("TP_PG_PORT")
var psqlport int
if psqlports == "" {
psqlport, err = beego.AppConfig.Int("psqlport")
if err != nil {
log.Fatalf("Failed to get psqlport: %v", err)
}
checkErr(err, "Failed to get psqlport")
} else {
psqlport, err = strconv.Atoi(psqlports)
if err != nil {
log.Fatalf("Failed to convert psqlports to int: %v", err)
}
checkErr(err, "Failed to convert psqlports to int")
}

psqldb, err := beego.AppConfig.String("psqldb")
if err != nil {
log.Fatalf("Failed to get psqldb: %v", err)
}
checkErr(err, "Failed to get psqldb")

// 构建数据源字符串
dataSource := fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s sslmode=disable TimeZone=Asia/Shanghai",
psqladdr,
psqlport,
Expand All @@ -61,21 +53,28 @@ func init() {
psqlpass,
)

a, err := gormadapter.NewAdapter("postgres", dataSource, false) // 设置为 false 以禁止自动创建表
if err != nil {
log.Fatalf("Failed to create new adapter: %v", err)
}
// 创建一个GORM DB实例
dsn := dataSource
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
checkErr(err, "Failed to open gorm db")

// 使用GORM DB实例和表名创建Casbin适配器,而不检查或创建表\
a, err := gormadapter.NewAdapterByDBUseTableName(db, "postgres", "casbin_rule")
checkErr(err, "Failed to create new adapter")

// 创建和配置Casbin执行器
e, err := casbin.NewEnforcer("initialize/casbin/model.conf", a)
if err != nil {
log.Fatalf("Failed to create new enforcer: %v", err)
}
checkErr(err, "Failed to create new enforcer")

CasbinEnforcer = e
err = CasbinEnforcer.LoadPolicy()
if err != nil {
log.Fatalf("Failed to load policy: %v", err)
}
checkErr(err, "Failed to load policy")

log.Println("casbin启动完成")
}

func checkErr(err error, msg string) {
if err != nil {
log.Fatalf("%s: %v", msg, err)
}
}
17 changes: 0 additions & 17 deletions middleware/auth_middle.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,6 @@ func AuthMiddle() {
// 解析token
userMsg, err := utils.ParseCliamsToken(userToken)
if err != nil {
// authorization := ctx.Request.Header["Authorization"][0]
// userToken := authorization[7:]
// _, err := jwt.ParseCliamsToken(userToken)
// if err != nil || redis.GetStr(userToken) != "1" {
// 异常
utils.SuccessWithMessage(401, ErrUnauthorized, (*context2.Context)(ctx))
return
}
Expand All @@ -65,18 +60,6 @@ func AuthMiddle() {
utils.SuccessWithMessage(401, err.Error(), (*context2.Context)(ctx))
return
}

// 验证用户是否存在
// 双层校验
// if psql.Mydb.Where("id = ? and name = ? ", user.ID, user.Name).First(&models.Users{}).Error == gorm.ErrRecordNotFound {
// response.SuccessWithMessage(401, "Unauthorized", (*context2.Context)(ctx))
// return
// }
// s, _ := cache.Bm.IsExist(c.TODO(), userToken)
// if !s {
// response.SuccessWithMessage(401, "Unauthorized", (*context2.Context)(ctx))
// return
// }
}
}
adapter.InsertFilter("/api/*", adapter.BeforeRouter, filterLogin)
Expand Down
2 changes: 2 additions & 0 deletions routers/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,8 @@ func init() {
web.NSRouter("/kv/history/key", &controllers.KvController{}, "*:GetHistoryDataByKey"),
// 通过设备ID、key查询某个时间范围内的设备统计类数据
web.NSRouter("/kv/statistic", &controllers.KvController{}, "*:GetStatisticDataByKey"),
// 通过设备id、key删除设备历史数据
web.NSRouter("/kv/history/delete", &controllers.KvController{}, "*:DeleteHistoryData"),
// 系统设置接口
web.NSRouter("/system/logo/index", &controllers.LogoController{}, "*:Index"), //ty
//常规设置修改
Expand Down
20 changes: 20 additions & 0 deletions services/tskv_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,26 @@ func (*TSKVService) GetHistoryData(device_id string, attributes []string, startT
return rsp_map, nil
}

// 通过设备ID删除历史数据
func (*TSKVService) DeleteHistoryData(device_id string, attributes string) (bool, error) {
var ts_kvs []models.TSKV
var ts_kv_latest []models.TSKVLatest

result1 := psql.Mydb.Where(" entity_id = ? AND key = ?", device_id, attributes).Delete(&ts_kvs)
if result1.Error != nil {
logs.Error(result1.Error.Error())
return false, result1.Error
}

result2 := psql.Mydb.Where(" entity_id = ? AND key = ?", device_id, attributes).Delete(&ts_kv_latest)
if result2.Error != nil {
logs.Error(result2.Error.Error())
return false, result2.Error
}

return true, nil
}

// 返回最新一条的设备数据,用来判断设备状态(待接入,异常,正常)
func (*TSKVService) Status(device_id string) (*models.TSKVLatest, int64) {
var TSKVLatest models.TSKVLatest
Expand Down
5 changes: 5 additions & 0 deletions validate/kv_validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,8 @@ type StatisticDataValidate struct {
AggregateWindow string `json:"aggregate_window" alias:"聚合间隔"`
AggregateFunction string `json:"aggregate_function" alias:"聚合方法"`
}
// 删除历史数据校验
type DeleteHistoryDataValidate struct {
DeviceId string `json:"device_id" alias:"设备" valid:"Required;MaxSize(36)"`
Attribute string `json:"attribute" alias:"属性" valid:"Required;MaxSize(36)"`
}

0 comments on commit ef65d87

Please sign in to comment.