lijian 6 سال پیش
والد
کامیت
05116dc014

+ 3 - 0
pkg/models/alarmrule.go

@@ -29,6 +29,9 @@ type AlarmRule struct {
 	NoticeWay    int    //通知方式 1:短信通知<br>2:极光推送<br>3:微信通知<br>
 	ProductID    int    //关联的产品ID
 	VendorID     uint   //关联厂商ID
+	StartIndex   int    //字符串或字节数组的开始位置
+	EndIndex     int    //字符串或字节数组的结束位置
+	Status       int    //状态,1正常,0禁用
 }
 
 // Validate 验证

+ 30 - 16
pkg/models/user.go

@@ -21,28 +21,12 @@ type User struct {
 	Vendor     Vendor `gorm:"foreignkey:VendorID"`
 }
 
-// Validate 验证
-func (a *User) Validate() error {
-	if a.UserName == "" || a.UserPass == "" || a.Vendor.VendorName == "" {
-		return errors.New("参数不能为空")
-	}
-	return nil
-}
-
 // LoginRequest 登录请求
 type LoginRequest struct {
 	UserName string `json:"login_name" `
 	Password string `json:"login_pass" `
 }
 
-// Validate 验证
-func (a *LoginRequest) Validate() error {
-	if a.UserName == "" || a.Password == "" {
-		return errors.New("参数不能为空")
-	}
-	return nil
-}
-
 // Reqrequest 注册请求
 type Reqrequest struct {
 	UserName   string `json:"username"`
@@ -52,6 +36,20 @@ type Reqrequest struct {
 	VendorName string `json:"company"`
 }
 
+// ChangePassWordRequest 修改密码请求结构
+type ChangePassWordRequest struct {
+	OldPass string `json:"old_pass"`
+	NewPass string `json:"new_pass"`
+}
+
+// Validate 验证
+func (a *ChangePassWordRequest) Validate() error {
+	if a.NewPass == "" || a.OldPass == "" {
+		return errors.New("非法参数")
+	}
+	return nil
+}
+
 // Validate 验证
 func (a *Reqrequest) Validate() error {
 	if a.UserName == "" || a.PassWord == "" || a.Phone == "" || a.Email == "" || a.VendorName == "" {
@@ -59,3 +57,19 @@ func (a *Reqrequest) Validate() error {
 	}
 	return nil
 }
+
+// Validate 验证
+func (a *LoginRequest) Validate() error {
+	if a.UserName == "" || a.Password == "" {
+		return errors.New("参数不能为空")
+	}
+	return nil
+}
+
+// Validate 验证
+func (a *User) Validate() error {
+	if a.UserName == "" || a.UserPass == "" || a.Vendor.VendorName == "" {
+		return errors.New("参数不能为空")
+	}
+	return nil
+}

+ 12 - 2
pkg/productconfig/productconfig.go

@@ -8,11 +8,13 @@ import (
 	"sparrow/pkg/tlv"
 )
 
+// CommandOrEventParam command or a event param struct
 type CommandOrEventParam struct {
 	ValueType int32 `json:"value_type"`
 	Name      string
 }
 
+// ProductCommandOrEvent ``
 type ProductCommandOrEvent struct {
 	No       int
 	Part     int
@@ -21,11 +23,14 @@ type ProductCommandOrEvent struct {
 	Params   []CommandOrEventParam
 }
 
+// StatusParam 上报类型的参数
 type StatusParam struct {
 	ValueType int32 `json:"value_type"`
 	Name      string
+	ID        uint `json:"pid"` //protocal id 与后台对应
 }
 
+// ProductObject 产品对象
 type ProductObject struct {
 	Id     int
 	No     int
@@ -34,13 +39,14 @@ type ProductObject struct {
 	Status []StatusParam
 }
 
-// product config parses the JSON product config string.
+// ProductConfig product config parses the JSON product config string.
 type ProductConfig struct {
 	Objects  []ProductObject
 	Commands []ProductCommandOrEvent
 	Events   []ProductCommandOrEvent
 }
 
+// New create a new productConfig
 func New(config string) (*ProductConfig, error) {
 	v := &ProductConfig{}
 	err := json.Unmarshal([]byte(config), v)
@@ -50,6 +56,7 @@ func New(config string) (*ProductConfig, error) {
 	return v, nil
 }
 
+// ValidateStatus validate the status
 func (config *ProductConfig) ValidateStatus(label string, params []interface{}) (*ProductObject, []interface{}, error) {
 	// search for status name
 	var paramInfo []StatusParam
@@ -76,6 +83,7 @@ func (config *ProductConfig) ValidateStatus(label string, params []interface{})
 	return status, realParams, nil
 }
 
+// ValidateCommandOrEvent validate command or event
 func (config *ProductConfig) ValidateCommandOrEvent(name string, params []interface{}, typ string) (*ProductCommandOrEvent, []interface{}, error) {
 	var target []ProductCommandOrEvent
 	if typ == "command" {
@@ -111,6 +119,7 @@ func (config *ProductConfig) ValidateCommandOrEvent(name string, params []interf
 	return coe, realParams, nil
 }
 
+// StatusToMap struct to map
 func (config *ProductConfig) StatusToMap(status []protocol.SubData) (map[string][]interface{}, error) {
 	result := make(map[string][]interface{})
 
@@ -131,9 +140,9 @@ func (config *ProductConfig) StatusToMap(status []protocol.SubData) (map[string]
 	return result, nil
 }
 
+// EventToMap event ot map
 func (config *ProductConfig) EventToMap(event *protocol.Event) (map[string][]interface{}, error) {
 	result := make(map[string][]interface{})
-
 	name := ""
 	for _, ev := range config.Events {
 		if ev.No == int(event.Head.No) {
@@ -150,6 +159,7 @@ func (config *ProductConfig) EventToMap(event *protocol.Event) (map[string][]int
 	return result, nil
 }
 
+// MapToStatus map to status
 func (config *ProductConfig) MapToStatus(data map[string]interface{}) ([]protocol.SubData, error) {
 	result := []protocol.SubData{}
 

+ 136 - 0
services/knowoapi/controllers/alert.go

@@ -0,0 +1,136 @@
+package controllers
+
+import (
+	"sparrow/pkg/models"
+	"sparrow/services/knowoapi/services"
+
+	"github.com/kataras/iris"
+	"github.com/kataras/iris/mvc"
+)
+
+//AlertController api
+type AlertController struct {
+	Ctx     iris.Context
+	Service services.AlertService
+	Token   Token
+}
+
+// Post 添加告警规则
+// POST /alert
+func (a *AlertController) Post() {
+	alert := new(models.AlarmRule)
+	if err := parseBody(a.Ctx, alert); err != nil {
+		badRequest(a.Ctx, err)
+		return
+	}
+	alert.VendorID = a.Token.getVendorID(a.Ctx)
+	err := a.Service.Create(alert)
+	if err != nil {
+		responseError(a.Ctx, ErrDatabase, err.Error())
+		return
+	}
+	done(a.Ctx, alert)
+}
+
+//Delete 删除
+// DELETE /alert
+func (a *AlertController) Delete() {
+	alert := new(models.AlarmRule)
+	if err := parseBody(a.Ctx, alert); err != nil {
+		badRequest(a.Ctx, err)
+		return
+	}
+	if alert.VendorID != a.Token.getVendorID(a.Ctx) {
+		responseError(a.Ctx, ErrNormal, "没有权限")
+		return
+	}
+	err := a.Service.Delete(alert)
+	if err != nil {
+		responseError(a.Ctx, ErrDatabase, "删除失败"+err.Error())
+		return
+	}
+	done(a.Ctx, "删除成功")
+}
+
+// Put 删除
+// PUT /alert
+func (a *AlertController) Put() {
+	alert := new(models.AlarmRule)
+	if err := parseBody(a.Ctx, alert); err != nil {
+		badRequest(a.Ctx, err)
+		return
+	}
+	if alert.VendorID != a.Token.getVendorID(a.Ctx) {
+		responseError(a.Ctx, ErrNormal, "没有权限")
+		return
+	}
+
+	_alert, err := a.Service.Update(a.Token.getVendorID(a.Ctx), alert)
+	if err != nil {
+		responseError(a.Ctx, ErrDatabase, err.Error())
+		return
+	}
+	done(a.Ctx, _alert)
+}
+
+// GetBy 根据ID查询
+// GET /alert/{id}
+func (a *AlertController) GetBy(id int) {
+	alert, err := a.Service.GetRule(a.Token.getVendorID(a.Ctx), id)
+	if err != nil {
+		responseError(a.Ctx, ErrDatabase, err.Error())
+		return
+	}
+	done(a.Ctx, alert)
+}
+
+// Get 获取告警列表
+// GET /alert
+func (a *AlertController) Get() {
+	pi, err := a.Ctx.URLParamInt("pi")
+	if err != nil {
+		badRequest(a.Ctx, err)
+		return
+	}
+	ps, err := a.Ctx.URLParamInt("ps")
+	if err != nil {
+		badRequest(a.Ctx, err)
+		return
+	}
+	proid, err := a.Ctx.URLParamInt("proid")
+	if err != nil {
+		proid = 0
+	}
+	ptlid, err := a.Ctx.URLParamInt("ptlid")
+	if err != nil {
+		ptlid = 0
+	}
+	name := a.Ctx.URLParam("name")
+	ds, total, err := a.Service.GetAlarmRules(a.Token.getVendorID(a.Ctx), pi, ps, proid, ptlid, name)
+	if err != nil {
+		responseError(a.Ctx, ErrDatabase, err.Error())
+		return
+	}
+	done(a.Ctx, map[string]interface{}{
+		"list":  ds,
+		"total": total,
+	})
+
+}
+
+// BeforeActivation inside router
+func (a *AlertController) BeforeActivation(b mvc.BeforeActivation) {
+	b.Handle("POST", "/status/{alertid:int}/{status:int}", "SetStatus")
+}
+
+// SetStatus set rule status
+func (a *AlertController) SetStatus() {
+	id, _ := a.Ctx.Params().GetInt("alertid")
+	status, _ := a.Ctx.Params().GetInt("status")
+	alert, err := a.Service.SetRuleStatus(a.Token.getVendorID(a.Ctx), id, status)
+	if err != nil {
+		responseError(a.Ctx, ErrDatabase, err.Error())
+		return
+	}
+	done(a.Ctx, alert.Status)
+}

+ 20 - 2
services/knowoapi/controllers/user.go

@@ -2,6 +2,7 @@ package controllers
 
 import (
 	"sparrow/pkg/models"
+	"sparrow/pkg/server"
 	"sparrow/services/knowoapi/model"
 	"sparrow/services/knowoapi/services"
 
@@ -88,6 +89,23 @@ func (a *UserController) PostRegistry() {
 	})
 }
 
-func (a *UserController) PostFile() {
-
+// PutChange 修改密码
+// PUT /user/changepass
+func (a *UserController) PutChange() {
+	req := new(models.ChangePassWordRequest)
+	if err := parseBody(a.Ctx, req); err != nil {
+		badRequest(a.Ctx, err)
+		return
+	}
+	b, err := a.Service.ModifyPassword(a.Token.getRecorID(a.Ctx), req.OldPass, req.NewPass)
+	if err != nil {
+		server.Log.Error(err)
+		responseError(a.Ctx, ErrDatabase, err.Error())
+		return
+	}
+	if !b {
+		responseError(a.Ctx, ErrNormal, "原密码不正确")
+		return
+	}
+	done(a.Ctx, "修改成功")
 }

+ 2 - 2
services/knowoapi/main.go

@@ -33,10 +33,10 @@ func main() {
 	//cors
 	opts := cors.Options{
 		AllowedOrigins: []string{"*"},
-		AllowedHeaders: []string{"Content-Type"},
+		AllowedHeaders: []string{"Content-Type", "Authorization"},
 		AllowedMethods: []string{"POST", "GET", "DELETE", "PUT"},
 		ExposedHeaders: []string{"X-Header"},
-		Debug:          true,
+		//Debug:          true,
 	}
 	app.Use(cors.New(opts))
 	app.AllowMethods(iris.MethodOptions)

+ 12 - 1
services/knowoapi/model/alert.go

@@ -59,7 +59,7 @@ func (a *Alert) Update(vendorid uint, alert *models.AlarmRule) (data models.Alar
 // procalid:协议ID, 可选
 // name: 规则名称,可选,模糊搜索
 func (a *Alert) GetRules(vendorid uint, pi, ps, proid, protocalid int, name string) (datas []models.AlarmRule, total int, err error) {
-	tx := a.db.Where("vendor_id = ? and 1=1")
+	tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
 	if proid != 0 {
 		tx = tx.Where("product_id = ?")
 	}
@@ -98,3 +98,14 @@ func (a *Alert) CheckProtocalRuleCount(vendorid uint, protocalID int) (total int
 		Error
 	return
 }
+
+// SetRuleState 设置规则的可用、禁用状态
+func (a *Alert) SetRuleState(vendorid uint, id, status int) (data models.AlarmRule, err error) {
+	alert := &models.AlarmRule{
+		VendorID: vendorid,
+		Status:   status,
+	}
+	alert.ID = uint(id)
+	err = a.db.Model(&data).Update(alert).Error
+	return
+}

+ 1 - 1
services/knowoapi/model/user.go

@@ -65,7 +65,7 @@ func (a *User) LoginCheck(loginname, loginpass string) (bool, *models.User, erro
 }
 
 // UpdatePassword 更新密码
-func (a *User) UpdatePassword(userid int, oldpass, newpass string) (bool, error) {
+func (a *User) UpdatePassword(userid uint, oldpass, newpass string) (bool, error) {
 	var count int
 	user := &models.User{}
 	err := a.db.Model(user).Where(map[string]interface{}{

+ 12 - 5
services/knowoapi/router.go

@@ -46,7 +46,7 @@ func registerRouters(srv *iris.Application, models *model.All, gen *generator.Ke
 	userService := services.NewUserService(models, gen)
 	appService := services.NewAppService(models, gen)
 	protocalService := services.NewProtocalService(models)
-
+	alertService := services.NewAlertService(models)
 	v1router := srv.Party("/api/v1")
 
 	// 登陆,注册
@@ -54,15 +54,22 @@ func registerRouters(srv *iris.Application, models *model.All, gen *generator.Ke
 	loginAPI.Register(userService).Handle(new(controllers.UserController))
 
 	// 用户接口组
-	userRouter := v1router.Party("/user")
+	userRouter := v1router.Party("/user", newJWThandle())
+
+	// user api
+	userAPI := mvc.New(userRouter.Party("/"))
+	userAPI.Register(userService).Handle(new(controllers.UserController))
 	// product api
-	productAPI := mvc.New(userRouter.Party("/product", newJWThandle()))
+	productAPI := mvc.New(userRouter.Party("/product"))
 	productAPI.Register(pService).Handle(new(controllers.ProductController))
 	//application api
-	appAPI := mvc.New(userRouter.Party("/application", newJWThandle()))
+	appAPI := mvc.New(userRouter.Party("/application"))
 	appAPI.Register(appService).Handle(new(controllers.AppController))
 	// protocal api
-	protocalAPI := mvc.New(userRouter.Party("/protocal", newJWThandle()))
+	protocalAPI := mvc.New(userRouter.Party("/protocal"))
 	protocalAPI.Register(protocalService).Handle(new(controllers.ProtocalController))
+	//alert api
+	alertAPI := mvc.New(userRouter.Party("/alert"))
+	alertAPI.Register(alertService).Handle(new(controllers.AlertController))
 
 }

+ 17 - 6
services/knowoapi/services/alert.go

@@ -1,6 +1,7 @@
 package services
 
 import (
+	"errors"
 	"sparrow/pkg/models"
 	"sparrow/services/knowoapi/model"
 )
@@ -17,33 +18,40 @@ type AlertService interface {
 	// name: 规则名称,可选,模糊搜索
 	GetAlarmRules(vendorid uint, pi, ps, proid, protocalid int, name string) ([]models.AlarmRule, int, error)
 	GetRule(vendorid uint, alertid int) (models.AlarmRule, error)
+	// 设置禁用可用状态
+	// 参数(vendorid, recordid, status)
+	SetRuleStatus(uint, int, int) (models.AlarmRule, error)
 }
 
 type alert struct {
 	model *model.All
 }
 
-// NewAlert create a alert back a  AlertService interface
-func NewAlert(model *model.All) AlertService {
+// NewAlertService create a alert back a  AlertService interface
+func NewAlertService(model *model.All) AlertService {
 	return alert{
 		model: model,
 	}
 }
 
 func (a alert) Create(alert *models.AlarmRule) error {
-	_, err := a.model.Alert.CheckProtocalRuleCount(alert.VendorID, alert.ProtocalID)
+	count, err := a.model.Alert.CheckProtocalRuleCount(alert.VendorID, alert.ProtocalID)
 	if err != nil {
 		return err
 	}
-	return nil
+	if count > 0 {
+		return errors.New("此协议已经设置告警规则")
+	}
+
+	return a.model.Alert.Create(alert)
 }
 
 func (a alert) Delete(alert *models.AlarmRule) error {
-	return nil
+	return a.model.Alert.Delete(alert)
 }
 
 func (a alert) Update(vendorid uint, alert *models.AlarmRule) (models.AlarmRule, error) {
-	return models.AlarmRule{}, nil
+	return a.model.Alert.Update(vendorid, alert)
 }
 func (a alert) GetAlarmRules(vendorid uint, pi, ps, proid, protocalid int, name string) ([]models.AlarmRule, int, error) {
 	return a.model.Alert.GetRules(vendorid, pi, ps, proid, protocalid, name)
@@ -51,3 +59,6 @@ func (a alert) GetAlarmRules(vendorid uint, pi, ps, proid, protocalid int, name
 func (a alert) GetRule(vendorid uint, alertid int) (models.AlarmRule, error) {
 	return a.model.Alert.GetAlarmRule(vendorid, alertid)
 }
+func (a alert) SetRuleStatus(vendorid uint, alertid int, status int) (models.AlarmRule, error) {
+	return a.model.Alert.SetRuleState(vendorid, alertid, status)
+}

+ 8 - 5
services/knowoapi/services/user.go

@@ -1,6 +1,7 @@
 package services
 
 import (
+	"encoding/base64"
 	"sparrow/pkg/generator"
 	"sparrow/pkg/models"
 	"sparrow/pkg/utils"
@@ -13,8 +14,8 @@ type UserService interface {
 	Login(*models.LoginRequest) (bool, *models.User, error)
 	// 注册
 	Register(*models.Reqrequest) (*models.User, error)
-	// 修改密码
-	ModifyPassword(int, string, string) (bool, error)
+	// 修改密码,其中密码接收的是已经base64过的字符串
+	ModifyPassword(uint, string, string) (bool, error)
 	// check name exsits
 	CheckUserName(string) (bool, error)
 	// check phone number exsits
@@ -59,9 +60,11 @@ func (a userservice) Register(user *models.Reqrequest) (*models.User, error) {
 	_u.VendorID = vedor.ID
 	return _u, a.model.User.Create(_u)
 }
-func (a userservice) ModifyPassword(userid int, new, old string) (bool, error) {
-	old = utils.Md5(old + model.SignedString)
-	new = utils.Md5(new + model.SignedString)
+func (a userservice) ModifyPassword(userid uint, new, old string) (bool, error) {
+	obytes, _ := base64.StdEncoding.DecodeString(old)
+	nbytes, _ := base64.StdEncoding.DecodeString(new)
+	old = utils.Md5(string(obytes) + model.SignedString)
+	new = utils.Md5(string(nbytes) + model.SignedString)
 	return a.model.User.UpdatePassword(userid, new, old)
 }