caipin 3 年之前
父節點
當前提交
f35256d4e7

+ 1 - 1
bootstrap/bootstrap.go

@@ -178,7 +178,7 @@ func (b *Bootstrapper) Bootstrap() *Bootstrapper {
 	// 	[]byte("lot-secret-of-characters-big-too"),
 	// )
 	// 设置csrf
-	b.SetupCsrfHandlers(CsrfKey)
+	// b.SetupCsrfHandlers(CsrfKey)
 	// 设置jwt
 	//b.SetupJwtHandlers(JwtKey)
 	// 设置rpc

+ 3 - 0
conf/project.go

@@ -38,6 +38,9 @@ var SignSecret = "cpcm005687gokaif"
 // cookie中的加密验证密钥
 var CookieSecret = "cm_login_account"
 
+// 计量,项目管理互通 请求
+var JLSecretKey = "JL_CM_lksjdofuosdjflj01231209uljsf90@@#(lnm8"
+
 // nodejs rpc 服务端
 const NodeRpcHost = "192.168.1.47:50051"
 

+ 1 - 0
dao/project_dao.go

@@ -211,6 +211,7 @@ func (d *ProjectDao) GetPageBs(pageData viewmodels.ProjectPage) (data []models.C
 //设置的值获得数据
 func (d *ProjectDao) GetCode(code string) *models.CmProject {
 	data := &models.CmProject{}
+
 	ok, err := d.engine.
 		Where("code = ?", code).
 		Get(data)

+ 1 - 1
datasource/dbhelper.go

@@ -62,7 +62,7 @@ func NewDbMaster() *xorm.Engine {
 	if err := v.Unmarshal(&conf.MysqlConfig); err != nil {
 		panic(err)
 	}
-
+	fmt.Println(conf.MysqlConfig)
 	sourcename := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
 		conf.MysqlConfig.User,
 		conf.MysqlConfig.Pwd,

+ 40 - 0
services/jl_service.go

@@ -0,0 +1,40 @@
+/*
+ * @description: 计量业务相关
+ * @Author: CP
+ * @Date: 2021-12-25 14:37:01
+ * @FilePath: \construction_management\services\jl_service.go
+ */
+package services
+
+import (
+	"go.mod/dao"
+	"go.mod/datasource"
+)
+
+type JlService struct {
+	dao *dao.ProjectDao
+}
+
+// 创建项目用户service
+func NewJlService() *JlService {
+	return &JlService{
+		dao: dao.NewProjectDao(datasource.InstanceDbMaster()),
+	}
+}
+
+// 是否有项目
+func (s *JlService) IsCode(code string) map[string]interface{} {
+	exist := 0
+	if code != "" {
+		projectData := s.dao.GetListByCode(code)
+		if len(projectData) != 0 {
+			exist = 1
+		}
+	}
+
+	data := map[string]interface{}{
+		"exist": exist,
+	}
+
+	return data
+}

+ 1 - 0
services/login_service.go

@@ -65,6 +65,7 @@ func (s *loginService) ValidProjectAccount(loginData viewmodels.Login, writer ht
 
 	// 1-1.工程项目是否存在
 	projectInfo := s.projectDao.GetCode(loginData.Code)
+
 	if projectInfo.Id == 0 {
 		return nil, errors.New("工程建设管理员还未创建项目,禁止登录")
 	}

+ 63 - 0
web/external/jl_ex.go

@@ -0,0 +1,63 @@
+/*
+ * @description: 计量接口
+ * @Author: CP
+ * @Date: 2021-12-25 14:33:40
+ * @FilePath: \construction_management\web\external\jl_ex.go
+ */
+package external
+
+import (
+	"fmt"
+
+	"github.com/kataras/iris/v12"
+	"go.mod/services"
+	"go.mod/web/utils"
+	"go.mod/web/viewmodels"
+)
+
+type JlEx struct {
+	//框架-web应用上下文环境
+	Ctx iris.Context
+	// 需要用的service - 必须是鸭子形式,才不会出现问题
+	// JlService services.JlService
+}
+
+// 检验项目 Calibration
+func (c *JlEx) PostCalibration() {
+
+	// 1.获得数据
+	data := &viewmodels.Jl{}
+	if err := c.Ctx.ReadForm(data); err != nil {
+		c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
+		return
+	}
+
+	// 1-1.校验是否存在TOKEN
+	if err := data.ValidateToken(); err != nil {
+		c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
+		return
+	}
+
+	// 1-2.验证jwt
+	claims, err := utils.ValidateJwt(data.Token)
+	if err != nil {
+		c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
+		return
+	}
+	// 1-3.验证参数的正确性
+	claimsData := &viewmodels.Jl{
+		Code: fmt.Sprintf("%s", claims["code"]),
+	}
+	if err := claimsData.ValidateParameter(); err != nil {
+		c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
+		return
+	}
+
+	JlService := services.NewJlService()
+	result := JlService.IsCode(claimsData.Code)
+	c.Ctx.JSON(iris.Map{
+		"code": 0,
+		"msg":  "",
+		"data": result,
+	})
+}

+ 1 - 0
web/middleware/jwt.go

@@ -20,6 +20,7 @@ type ResModel struct {
 }
 
 func JwtAuth() *jwt.Middleware {
+
 	j2 := jwt.New(jwt.Config{
 		// 注意,新增了一个错误处理函数
 		ErrorHandler: func(ctx iris.Context, err error) {

+ 33 - 21
web/routes/routes.go

@@ -7,11 +7,14 @@
 package routes
 
 import (
+	"github.com/iris-contrib/middleware/csrf"
+	"github.com/kataras/iris/v12"
 	"github.com/kataras/iris/v12/mvc"
 	"go.mod/bootstrap"
 	"go.mod/services"
 	"go.mod/web/api"
 	"go.mod/web/backstage"
+	"go.mod/web/external"
 	"go.mod/web/middleware"
 )
 
@@ -41,6 +44,10 @@ func Configure(b *bootstrap.Bootstrapper) {
 	//CSRF相关
 	b.Use(middleware.SetCsrf)
 
+	protect := csrf.Protect([]byte("9AB0F421E53A477C084477AEA06096F5"), csrf.FieldName("csrf"), csrf.Secure(false), csrf.Path("/"), csrf.ErrorHandler(func(ctx iris.Context) {
+		ctx.JSON(iris.Map{"code": -1, "msg": "CSRF token invalid"})
+	}))
+
 	//b.Party("/", protect)
 	//protect := NewCsrf()
 
@@ -96,35 +103,35 @@ func Configure(b *bootstrap.Bootstrapper) {
 	// apiTree.Router.Use(middleware.JwtAuth().Serve)
 	// 接口相关
 	// 登陆接口
-	apiLogin := mvc.New(b.Party("/api/login"))
+	apiLogin := mvc.New(b.Party("/api/login", protect))
 	apiLogin.Register(ProjectAccountService)
 	apiLogin.Register(LoginService)
 	apiLogin.Register(ProjectService)
 	apiLogin.Handle(new(api.LoginApi))
 
 	// 项目相关接口
-	apiProject := mvc.New(b.Party("/api/project"))
+	apiProject := mvc.New(b.Party("/api/project", protect))
 	apiProject.Register(ProjectService)
 	apiProject.Router.Use(middleware.SessionsAuth)
 	apiProject.Router.Use(middleware.AccessAuth)
 	apiProject.Handle(new(api.ProjectApi))
 
 	// 项目账号相关接口
-	apiProjectAccount := mvc.New(b.Party("/api/projectAccount"))
+	apiProjectAccount := mvc.New(b.Party("/api/projectAccount", protect))
 	apiProjectAccount.Register(ProjectAccountService)
 	apiProjectAccount.Router.Use(middleware.SessionsAuth)
 	apiProjectAccount.Router.Use(middleware.AccessAuth)
 	apiProjectAccount.Handle(new(api.ProjectAccountApi))
 
 	// 标段相关接口
-	apiBidsection := mvc.New(b.Party("/api/bidsection"))
+	apiBidsection := mvc.New(b.Party("/api/bidsection", protect))
 	apiBidsection.Register(BidsectionService)
 	apiBidsection.Router.Use(middleware.SessionsAuth)
 	apiBidsection.Router.Use(middleware.AccessAuth)
 	apiBidsection.Handle(new(api.BidsectionApi))
 
 	// 项目设置接口
-	apiSetting := mvc.New(b.Party("/api/projectSetting"))
+	apiSetting := mvc.New(b.Party("/api/projectSetting", protect))
 	apiSetting.Register(ProjectAccountService)
 	apiSetting.Register(ProjectService)
 	apiSetting.Register(BidAccountService)
@@ -133,14 +140,14 @@ func Configure(b *bootstrap.Bootstrapper) {
 	apiSetting.Handle(new(api.ProjectSettingApi))
 
 	// TreeNode相关接口
-	apiTree := mvc.New(b.Party("/api/tree"))
+	apiTree := mvc.New(b.Party("/api/tree", protect))
 	apiTree.Register(TreeService)
 	apiTree.Router.Use(middleware.SessionsAuth)
 	apiTree.Router.Use(middleware.AccessAuth)
 	apiTree.Handle(new(api.TreeApi))
 
 	// 合同管理
-	apiContract := mvc.New(b.Party("/api/contract"))
+	apiContract := mvc.New(b.Party("/api/contract", protect))
 	apiContract.Register(TreeService)
 	apiContract.Register(ContractService)
 	// 中间件
@@ -149,7 +156,7 @@ func Configure(b *bootstrap.Bootstrapper) {
 	apiContract.Handle(new(api.ContractApi))
 
 	// oss相关
-	apiOss := mvc.New(b.Party("/api/oss"))
+	apiOss := mvc.New(b.Party("/api/oss", protect))
 	apiOss.Router.Use(middleware.SessionsAuth)
 	apiOss.Router.Use(middleware.AccessAuth)
 	apiOss.Handle(new(api.OssApi))
@@ -162,45 +169,45 @@ func Configure(b *bootstrap.Bootstrapper) {
 	// rpc.Handle(new(api.RpcApi))
 
 	// safe
-	apiSafe := mvc.New(b.Party("/api/safe"))
+	apiSafe := mvc.New(b.Party("/api/safe", protect))
 	apiSafe.Register(SafeService)
 	apiSafe.Router.Use(middleware.SessionsAuth)
 	apiSafe.Router.Use(middleware.AccessAuth)
 	apiSafe.Handle(new(api.SafeApi))
 
-	apiSafeAudit := mvc.New(b.Party("/api/safe_audit"))
+	apiSafeAudit := mvc.New(b.Party("/api/safe_audit", protect))
 	apiSafeAudit.Register(SafeAuditService)
 	apiSafeAudit.Router.Use(middleware.SessionsAuth)
 	apiSafeAudit.Router.Use(middleware.AccessAuth)
 	apiSafeAudit.Handle(new(api.SafeAuditApi))
 
 	// quality
-	apiQuality := mvc.New(b.Party("/api/quality"))
+	apiQuality := mvc.New(b.Party("/api/quality", protect))
 	apiQuality.Register(QualityService)
 	apiQuality.Router.Use(middleware.SessionsAuth)
 	apiQuality.Router.Use(middleware.AccessAuth)
 	apiQuality.Handle(new(api.QualityApi))
 
-	apiQualityAudit := mvc.New(b.Party("/api/quality_audit"))
+	apiQualityAudit := mvc.New(b.Party("/api/quality_audit", protect))
 	apiQualityAudit.Register(QualityAuditService)
 	apiQualityAudit.Router.Use(middleware.SessionsAuth)
 	apiQualityAudit.Router.Use(middleware.AccessAuth)
 	apiQualityAudit.Handle(new(api.QualityAuditApi))
 	// rule
-	apiRule := mvc.New(b.Party("/api/rule"))
+	apiRule := mvc.New(b.Party("/api/rule", protect))
 	apiRule.Register(RuleService)
 	apiRule.Router.Use(middleware.SessionsAuth)
 	apiRule.Router.Use(middleware.AccessAuth)
 	apiRule.Handle(new(api.RuleApi))
 
 	// file
-	apiAnnex := mvc.New(b.Party("/api/file"))
+	apiAnnex := mvc.New(b.Party("/api/file", protect))
 	apiAnnex.Register(AnnexService)
 	apiAnnex.Router.Use(middleware.SessionsAuth)
 	apiAnnex.Router.Use(middleware.AccessAuth)
 	apiAnnex.Handle(new(api.AnnexApi))
 
-	apiDashboard := mvc.New(b.Party("/api/dashboard"))
+	apiDashboard := mvc.New(b.Party("/api/dashboard", protect))
 	apiDashboard.Register(SafeService)
 	apiDashboard.Register(QualityService)
 	apiDashboard.Register(ProjectMessageService)
@@ -209,19 +216,23 @@ func Configure(b *bootstrap.Bootstrapper) {
 	apiDashboard.Router.Use(middleware.AccessAuth)
 	apiDashboard.Handle(new(api.DashboardApi))
 
+	// 对计量接口
+	jlEx := mvc.New(b.Party("/api/external/jl"))
+	jlEx.Handle(new(external.JlEx))
+
 	// 后台相关
-	backstageCM := mvc.New(b.Party("/api/backstage/login"))
+	backstageCM := mvc.New(b.Party("/api/backstage/login", protect))
 	backstageCM.Register(backstageService)
 	backstageCM.Handle(new(backstage.LoginBs))
 
-	backstageProjectCM := mvc.New(b.Party("/api/backstage/project"))
+	backstageProjectCM := mvc.New(b.Party("/api/backstage/project", protect))
 	backstageProjectCM.Register(ProjectService)
 	backstageProjectCM.Register(backstageService)
 	backstageProjectCM.Router.Use(middleware.SessionsBackstageAuth)
 	backstageProjectCM.Router.Use(middleware.AccessBackstageAuth)
 	backstageProjectCM.Handle(new(backstage.ProjectBs))
 
-	backstageAccountCM := mvc.New(b.Party("/api/backstage/account"))
+	backstageAccountCM := mvc.New(b.Party("/api/backstage/account", protect))
 	backstageAccountCM.Register(ProjectAccountService)
 	backstageAccountCM.Register(ProjectService)
 	backstageAccountCM.Register(BidAccountService)
@@ -230,18 +241,19 @@ func Configure(b *bootstrap.Bootstrapper) {
 	backstageAccountCM.Router.Use(middleware.AccessBackstageAuth)
 	backstageAccountCM.Handle(new(backstage.ProjectAccountBs))
 
-	managerCM := mvc.New(b.Party("/api/backstage/manager"))
+	managerCM := mvc.New(b.Party("/api/backstage/manager", protect))
 	managerCM.Register(managerService)
 	managerCM.Router.Use(middleware.SessionsBackstageAuth)
 	managerCM.Handle(new(backstage.ManagerBs))
 
-	groupCM := mvc.New(b.Party("/api/backstage/group"))
+	groupCM := mvc.New(b.Party("/api/backstage/group", protect))
 	groupCM.Register(groupService)
 	groupCM.Router.Use(middleware.SessionsBackstageAuth)
 	groupCM.Handle(new(backstage.GroupBs))
 
-	versionCM := mvc.New(b.Party("/api/backstage/version"))
+	versionCM := mvc.New(b.Party("/api/backstage/version", protect))
 	versionCM.Register(versionService)
 	versionCM.Router.Use(middleware.SessionsBackstageAuth)
 	versionCM.Handle(new(backstage.VersionBs))
+
 }

+ 40 - 0
web/utils/utils.go

@@ -9,9 +9,12 @@ package utils
 import (
 	"errors"
 	"fmt"
+	"log"
 	"strconv"
 	"strings"
+	"time"
 
+	"github.com/dgrijalva/jwt-go"
 	"github.com/kataras/iris/v12"
 	"go.mod/comm"
 	"go.mod/conf"
@@ -132,6 +135,43 @@ func CreateRuleCode(code int64, count int64, len int) string {
 	}
 }
 
+// 验证并解析JWT
+func ValidateJwt(tokenStr string) (jwt.MapClaims, error) {
+	// 0.测试时使用
+	// 在这里声明令牌的到期时间,我们将其保留为5分钟
+	expirationTime := time.Now().Add(5 * time.Minute)
+	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
+		"code":    "gs01",
+		"isAdmin": 1,
+		"StandardClaims": jwt.StandardClaims{
+			ExpiresAt: expirationTime.Unix(),
+		},
+	})
+	tokenString, _ := token.SignedString([]byte(conf.JLSecretKey))
+	log.Println("JWT 5分钟过期-开发使用,=", tokenString)
+
+	// 1.验证并解析JWT
+	parseAuth, err := jwt.Parse(tokenStr, func(*jwt.Token) (interface{}, error) {
+		return []byte(conf.JLSecretKey), nil
+	})
+	if err != nil {
+		log.Println("JWT异常, error=", err)
+		return nil, err
+	}
+	if !parseAuth.Valid {
+		return nil, errors.New("无效签名")
+	}
+
+	// 1-2.转换为map
+	claims := parseAuth.Claims.(jwt.MapClaims)
+
+	// if err := json.Unmarshal(tokData, &claims); err != nil {
+	// 	return nil, err
+	// }
+
+	return claims, nil
+}
+
 // // 获得项目ID
 // func GetProjectId(ctx iris.Context) (int, error) {
 // 	jwtInfo := ctx.Values().Get("jwt").(*jwt.Token)

+ 103 - 0
web/viewmodels/jl.go

@@ -0,0 +1,103 @@
+/*
+ * @description:
+ * @Author: CP
+ * @Date: 2021-12-25 15:06:19
+ * @FilePath: \construction_management\web\viewmodels\jl.go
+ */
+package viewmodels
+
+import (
+
+	// jwtmiddleware "github.com/iris-contrib/middleware/jwt"
+
+	validation "github.com/go-ozzo/ozzo-validation/v3"
+)
+
+type Jl struct {
+	Token string `form:"token" json:"token" `
+	Code  string `form:"code" json:"code" `
+}
+
+// 校验项目接口
+func (l Jl) ValidateToken() error {
+	return validation.ValidateStruct(&l,
+		validation.Field(&l.Token, validation.Required.Error("token不能为空")),
+	)
+}
+
+// 验证传参
+func (l Jl) ValidateParameter() error {
+	return validation.ValidateStruct(&l,
+		validation.Field(&l.Code, validation.Required.Error("token不能为空")),
+	)
+}
+
+// // 校验jwt
+// func (l Jl) ValidateJwt(tokenStr string, ctx iris.Context) (jwt.MapClaims, error) {
+
+// 	// 验证
+// 	// j := jwtmiddleware.New(jwtmiddleware.Config{
+// 	// 	// 返回一个密匙
+// 	// 	ValidationKeyGetter: func(token *jwt.Token) (i interface{}, e error) {
+// 	// 		return conf.JLSecretKey, nil
+// 	// 	},
+// 	// 	Extractor: jwtmiddleware.FromParameter("token"),
+
+// 	// 	SigningMethod: jwtmiddleware.SigningMethodHS256,
+// 	// })
+
+// 	// if err := j.CheckJWT(ctx); err != nil {
+// 	// 	fmt.Println(err)
+// 	// }
+
+// 	// 解析
+// 	// tokenClaims, err := jwt.ParseWithClaims(tokenStr, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
+// 	// 	return []byte(conf.JLSecretKey), nil
+// 	// })
+// 	// if err != nil {
+// 	// 	return nil, err
+// 	// }
+
+// 	// 初始化`Claims`实例
+// 	// claims := &Claims{}
+// 	// 解析JWT字符串并将结果存储在`claims`中。
+// 	// 请注意,我们也在此方法中传递了密钥。
+// 	// 如果令牌无效(如果令牌已根据我们设置的登录到期时间过期)或者签名不匹配,此方法会返回错误.
+// 	// tkn, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
+// 	// 	return []byte(conf.JLSecretKey), nil
+// 	// })
+
+// 	// 在这里声明令牌的到期时间,我们将其保留为5分钟
+// 	expirationTime := time.Now().Add(5 * time.Minute)
+
+// 	claims := &Claims{
+// 		Username: "蔡频",
+// 		StandardClaims: jwt.StandardClaims{
+// 			// In JWT, the expiry time is expressed as unix milliseconds
+// 			ExpiresAt: expirationTime.Unix(),
+// 		},
+// 	}
+
+// 	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
+// 	// 创建JWT字符串
+// 	tokenString, err := token.SignedString([]byte(conf.JLSecretKey))
+
+// 	fmt.Println(tokenString)
+// 	fmt.Println("tokenString")
+
+// 	parseAuth, err := jwt.Parse(tokenStr, func(*jwt.Token) (interface{}, error) {
+// 		return []byte(conf.JLSecretKey), nil
+// 	})
+// 	if err != nil {
+// 		log.Println("JWT异常, error=", err)
+// 		return nil, err
+// 	}
+// 	if !parseAuth.Valid {
+// 		return nil, errors.New("无效签名")
+// 	}
+// 	// claims := parseAuth.Claims.(jwt.MapClaims)
+
+// 	fmt.Println(claims)
+
+// 	return nil, nil
+// }