package controllers import ( "encoding/json" "fmt" "hongze/hz_crm_api/cache" "hongze/hz_crm_api/models/system" "hongze/hz_crm_api/services/alarm_msg" "hongze/hz_crm_api/services/data" "net/http" "net/url" "strconv" "strings" "time" "github.com/beego/beego/v2/server/web" "hongze/hz_crm_api/models" "hongze/hz_crm_api/utils" "github.com/rdlucklib/rdluck_tools/log" ) var apiLog *log.Log type AfterHandle func(bodyByte []byte) error // AfterHandlerUrlMap 结束后待处理的url var AfterHandlerUrlMap = map[string][]AfterHandle{ "/adminapi/datamanage/chart_info/save": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表保存接口 "/adminapi/datamanage/multiple_graph/chart/save": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //批量图表保存接口 //"/adminapi/datamanage/chart_info/detail": data.DeleteChartInfoDataRedis, "/adminapi/datamanage/chart_info/edit": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表编辑接口 "/adminapi/datamanage/chart_info/refresh": {data.DeleteChartInfoDataRedis}, //图表刷新接口 "/adminapi/datamanage/chart_info/add": {data.DeleteChartClassifyRedis}, //图表添加接口 "/adminapi/datamanage/chart_classify/delete": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表删除、图表分类删除 "/adminapi/datamanage/chart_classify/add": {data.DeleteChartClassifyRedis}, //新增图表分类接口 "/adminapi/datamanage/chart_classify/edit": {data.DeleteChartClassifyRedis}, //编辑图表分类接口 "/adminapi/datamanage/chart_classify/move": {data.DeleteChartClassifyRedis}, //移动图表分类接口 "/adminapi/datamanage/chart_info/move": {data.DeleteChartClassifyRedis}, //移动图表接口 "/adminapi/datamanage/chart_info/copy": {data.DeleteChartClassifyRedis}, //图表另存为接口 } var AdminOperateRecordMap = map[string]string{ "/adminapi/pptv2/saveLog": "/adminapi/pptv2/saveLog", "/adminapi/report/saveReportContent": "/adminapi/report/saveReportContent", "/adminapi/datamanage/chart_info/common/detail/from_unique_code": "/adminapi/datamanage/chart_info/common/detail/from_unique_code", "/adminapi/english_report/saveReportContent": "/adminapi/english_report/saveReportContent", "/adminapi/custom/message/listV2": "/adminapi/custom/message/listV2", "/adminapi/sysuser/check_pwd": "/adminapi/sysuser/check_pwd", "/adminapi/system/menu/list": "/adminapi/system/menu/list", } func init() { if utils.RunMode == "release" { logDir := `/data/rdlucklog/hongze_admin` apiLog = log.Init("20060102.api", logDir) } else { apiLog = log.Init("20060102.api") } } type BaseAuthController struct { web.Controller SysUser *system.Admin } func (this *BaseAuthController) Prepare() { fmt.Println("enter prepare") method := this.Ctx.Input.Method() uri := this.Ctx.Input.URI() fmt.Println("Url:", uri) if method != "HEAD" { if method == "POST" || method == "GET" { authorization := this.Ctx.Input.Header("authorization") if authorization == "" { authorization = this.Ctx.Input.Header("Authorization") } if authorization == "" { newAuthorization := this.GetString("authorization") if newAuthorization != `` { authorization = "authorization=" + newAuthorization } else { newAuthorization = this.GetString("Authorization") authorization = "authorization=" + newAuthorization } } else { if strings.Contains(authorization, ";") { authorization = strings.Replace(authorization, ";", "$", 1) } } if authorization == "" { strArr := strings.Split(uri, "?") for k, v := range strArr { fmt.Println(k, v) } if len(strArr) > 1 { authorization := strArr[1] authorization = strings.Replace(authorization, "Authorization", "authorization", -1) fmt.Println(authorization) } } if authorization == "" { this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false) this.StopRun() return } authorizationArr := strings.Split(authorization, "$") if len(authorizationArr) <= 1 { this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false) this.StopRun() return } tokenStr := authorizationArr[0] tokenArr := strings.Split(tokenStr, "=") token := tokenArr[1] accountStr := authorizationArr[1] accountArr := strings.Split(accountStr, "=") account := accountArr[1] //校验token是否合法 // JWT校验Token和Account if !utils.CheckToken(account, token) { this.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}, false, false) this.StopRun() return } session, err := system.GetSysSessionByToken(token) if err != nil { if err.Error() == utils.ErrNoRow() { this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false) this.StopRun() return } this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false) this.StopRun() return } if session == nil { this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false) this.StopRun() return } if time.Now().After(session.ExpiredTime) { this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false) this.StopRun() return } admin, err := system.GetSysUserById(session.SysUserId) if err != nil { if err.Error() == utils.ErrNoRow() { this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.SysUserId)}, false, false) this.StopRun() return } this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取admin信息异常,Eerr:" + err.Error()}, false, false) this.StopRun() return } if admin == nil { this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false) this.StopRun() return } //如果不是启用状态 if admin.Enabled != 1 { this.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!,CheckToken Fail"}, false, false) this.StopRun() return } // 如果当前登录态是不可信设备的,那么需要做过期校验 if session.IsRemember != 1 { loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id) loginInfo, _ := utils.Rc.RedisString(loginKey) if loginInfo == `` { this.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false) this.StopRun() return } if loginInfo != "1" { msg := `该账号于` + admin.LastLoginTime + "在其他网络登录。此客户端已退出登录。" this.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false) this.StopRun() return } utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute) // 不信任名单也同步更新 noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, admin.AdminId) utils.Rc.Put(noTrustLoginKey, session.Id, utils.LoginCacheTime*time.Minute) } admin.RoleTypeCode = GetSysUserRoleTypeCode(admin.RoleTypeCode) this.SysUser = admin } else { this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false) this.StopRun() return } } } func (c *BaseAuthController) ServeJSON(encoding ...bool) { urlPath := c.Ctx.Request.URL.Path // 方法处理完后,需要后置处理的业务逻辑 if handlerList, ok := AfterHandlerUrlMap[urlPath]; ok { for _, handler := range handlerList { handler(c.Ctx.Input.RequestBody) } } var ( hasIndent = false hasEncoding = false ) if web.BConfig.RunMode == web.PROD { hasIndent = false } if len(encoding) > 0 && encoding[0] == true { hasEncoding = true } if c.Data["json"] == nil { //go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers) body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值" go alarm_msg.SendAlarmMsg(body, 1) return } baseRes := c.Data["json"].(*models.BaseResponse) if baseRes != nil && baseRes.Ret != 408 { body, _ := json.Marshal(baseRes) var requestBody string method := c.Ctx.Input.Method() if method == "GET" { requestBody = c.Ctx.Request.RequestURI } else { //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody)) requestBody = string(c.Ctx.Input.RequestBody) } if baseRes.Ret != 200 && baseRes.IsSendEmail { //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "URI:"+c.Ctx.Input.URI()+"
"+"Params"+requestBody+"
"+"ErrMsg:"+baseRes.ErrMsg+";
Msg:"+baseRes.Msg+";
Body:"+string(body)+"
"+c.SysUser.RealName, utils.EmailSendToUsers) body := "URI:" + c.Ctx.Input.URI() + "
" + "Params" + requestBody + "
" + "ErrMsg:" + baseRes.ErrMsg + ";
Msg:" + baseRes.Msg + ";
Body:" + string(body) + "
" + c.SysUser.RealName go alarm_msg.SendAlarmMsg(body, 1) } if baseRes.IsAddLog && c.SysUser != nil { go cache.RecordNewLogs(c.SysUser.AdminId, requestBody, string(body), c.SysUser.RealName, c.Ctx.Input.IP(), c.Ctx.Input.URI()) } } //新增uuid记录 { if _, ok := AdminOperateRecordMap[urlPath]; !ok && !strings.Contains(urlPath, "cygx") { var adminId int var realName, params, ip, uriStr string ip = c.Ctx.Input.IP() if c.SysUser != nil { adminId = c.SysUser.AdminId realName = c.SysUser.RealName } uuid := c.Ctx.Input.Header("Uuid") userAgent := c.Ctx.Input.Header("User-Agent") uri := c.Ctx.Input.URI() uriStr, _ = url.PathUnescape(uri) if uriStr != "" { uri = uriStr } if c.Ctx.Input.Method() == "GET" { paramsJson, _ := json.Marshal(c.Ctx.Input.Params()) params = string(paramsJson) } else { params = string(c.Ctx.Input.RequestBody) } header := c.Ctx.Request.Header headerJson, _ := json.Marshal(header) headerStr := string(headerJson) go cache.AdminOperateRecord(adminId, realName, uuid, uri, params, ip, userAgent, headerStr) } } c.JSON(c.Data["json"], hasIndent, hasEncoding) } func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error { c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8") var content []byte var err error if hasIndent { content, err = json.MarshalIndent(data, "", " ") } else { content, err = json.Marshal(data) } if err != nil { http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError) return err } ip := c.Ctx.Input.IP() requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody)) if err != nil { requestBody = string(c.Ctx.Input.RequestBody) } if requestBody == "" { requestBody = c.Ctx.Input.URI() } apiLog.Println("请求地址:", c.Ctx.Input.URI(), "Authorization:", c.Ctx.Input.Header("Authorization"), "RequestBody:", requestBody, "ResponseBody", string(content), "IP:", ip) // 如果不是debug分支的话,那么需要加密返回 if utils.RunMode != "debug" { content = utils.DesBase64Encrypt(content) // get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧 content = []byte(`"` + string(content) + `"`) } if coding { content = []byte(utils.StringsToJSON(string(content))) } return c.Ctx.Output.Body(content) } func GetSysUserRoleTypeCode(roleTypeCode string) string { if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT { return utils.ROLE_TYPE_CODE_FICC_SELLER } if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT { return utils.ROLE_TYPE_CODE_RAI_SELLER } if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP { return utils.ROLE_TYPE_CODE_RAI_GROUP } if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { return utils.ROLE_TYPE_CODE_ADMIN } if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN { return utils.ROLE_TYPE_CODE_FICC_ADMIN } if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM { return utils.ROLE_TYPE_CODE_FICC_TEAM } if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP { return utils.ROLE_TYPE_CODE_FICC_GROUP } if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN { return utils.ROLE_TYPE_CODE_RAI_ADMIN } if roleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR { return utils.ROLE_TYPE_CODE_FICC_RESEARCHR } if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR { return utils.ROLE_TYPE_CODE_FICC_RESEARCHR } if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_RESEARCHR { return utils.ROLE_TYPE_CODE_RAI_RESEARCHR } //合规 if roleTypeCode == utils.ROLE_TYPE_CODE_COMPLIANCE { return utils.ROLE_TYPE_CODE_COMPLIANCE } //财务 if roleTypeCode == utils.ROLE_TYPE_CODE_FINANCE { return utils.ROLE_TYPE_CODE_FINANCE } return "" }