package controllers import ( "encoding/json" "eta_gn/eta_api/cache" "eta_gn/eta_api/models/system" "eta_gn/eta_api/services" "eta_gn/eta_api/services/alarm_msg" "eta_gn/eta_api/services/data" "fmt" "net/http" "net/url" "strconv" "strings" "time" "github.com/beego/beego/v2/server/web" "eta_gn/eta_api/models" "eta_gn/eta_api/utils" ) type AfterHandle func(bodyByte []byte) error 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/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", } type BaseAuthController struct { web.Controller SysUser *system.Admin Session *system.SysSession Lang string `description:"当前语言类型,中文:zh;英文:en;默认:zh"` } 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 { 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 = string(c.Ctx.Input.RequestBody) } if baseRes.Ret != 200 && baseRes.IsSendEmail { 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()) } } if utils.ViperConfig != nil { if c.Lang == utils.EnLangVersion { msg := c.Data["json"].(*models.BaseResponse).Msg if utils.ViperConfig.InConfig(msg) { c.Data["json"].(*models.BaseResponse).Msg = utils.ViperConfig.GetString(msg) } } } { 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") desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt) c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key c.Ctx.SetCookie("", "", -1, "/", "", false, true, "") 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() } c.logUri(content, requestBody, ip) if utils.RunMode != "debug" { content = utils.DesBase64Encrypt(content, utils.DesKey) 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 "" } func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) { authorization := "" method := c.Ctx.Input.Method() uri := c.Ctx.Input.URI() if method != "HEAD" { if method == "POST" || method == "GET" { authorization = c.Ctx.Input.Header("authorization") if authorization == "" { authorization = c.Ctx.Input.Header("Authorization") } if authorization == "" { newAuthorization := c.GetString("authorization") if newAuthorization != `` { authorization = "authorization=" + newAuthorization } else { newAuthorization = c.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) } } } } utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip) return } func (c *BaseAuthController) Prepare() { method := c.Ctx.Input.Method() if method == `HEAD` { c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false) c.StopRun() return } if method != "POST" && method != "GET" { c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false) c.StopRun() return } uri := c.Ctx.Input.URI() { lang := c.Ctx.Input.Header("Lang") if lang == "" { lang = utils.ZhLangVersion } c.Lang = lang } isOk, token, resp := checkToken(c) if !isOk { _ = c.JSON(resp, false, false) c.StopRun() return } session, err := system.GetSysSessionByToken(token) if err != nil { if utils.IsErrNoRow(err) { c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false) c.StopRun() return } c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false) c.StopRun() return } if session == nil { c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false) c.StopRun() return } account := utils.MD5(session.UserName) if !utils.CheckToken(account, token) { c.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败,请重新登录!", ErrMsg: "登录失效,请重新登陆!,CheckToken Fail"}, false, false) c.StopRun() return } if time.Now().After(session.ExpiredTime) { c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false) c.StopRun() return } admin, err := system.GetSysUserById(session.SysUserId) if err != nil { if utils.IsErrNoRow(err) { c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.SysUserId)}, false, false) c.StopRun() return } c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取admin信息异常,Eerr:" + err.Error()}, false, false) c.StopRun() return } if admin == nil { c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false) c.StopRun() return } if admin.Enabled != 1 { c.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常!", ErrMsg: "账户被禁用,不允许登陆!,CheckToken Fail"}, false, false) c.StopRun() return } if session.IsRemember != 1 { loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id) loginInfo, _ := utils.Rc.RedisString(loginKey) if loginInfo == `` { c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作,系统自动退出!", ErrMsg: "超时未操作,系统自动退出!"}, false, false) c.StopRun() return } if uri != `/adminapi/eta_trial/user/login_duration` && uri != `/adminapi/eta_trial/user/active` { 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) c.SysUser = admin c.Session = session roleId := admin.RoleId list, e := system.GetMenuButtonApisByRoleId(roleId) if e != nil { c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错!", ErrMsg: "获取接口权限出错!"}, false, false) c.StopRun() return } var api string for _, v := range list { if v.Api != "" { api += v.Api + "&" } } if publicApi, ok := models.BusinessConfMap["PublicApi"]; ok { api += "&" + publicApi } api = strings.TrimRight(api, "&") uri = strings.Replace(uri, "/adminapi", "", 1) uris := strings.Split(uri, "?") uri = uris[0] apis := strings.Split(api, "&") apiMap := make(map[string]bool, 0) for _, s := range apis { apiMap[s] = true } if !apiMap[uri] { c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false) c.StopRun() return } } func checkToken(c *BaseAuthController) (isOk bool, token string, resp models.BaseResponse) { isOk = true uri := c.Ctx.Input.URI() authorization := c.Ctx.Input.Header("authorization") if authorization == "" { authorization = c.Ctx.Input.Header("Authorization") } if authorization == "" { newAuthorization := c.GetString("authorization") if newAuthorization != `` { authorization = "authorization=" + newAuthorization } else { newAuthorization = c.GetString("Authorization") authorization = "authorization=" + newAuthorization } } else { if strings.Contains(authorization, ";") { authorization = strings.Replace(authorization, ";", "$", 1) } } if authorization == "" { strArr := strings.Split(uri, "?") if len(strArr) > 1 { authorization = strArr[1] authorization = strings.Replace(authorization, "Authorization", "authorization", -1) } } if authorization != "" { tokenStr := authorization tokenArr := strings.Split(tokenStr, "=") token = tokenArr[1] } aiUser := c.Ctx.GetCookie("ai_user") if aiUser == `` { aiUser = c.Ctx.GetCookie("ai_token") } fmt.Println("ai_user:", aiUser) if aiUser != "" { if token == `` { newLogin, e := services.UserLoginChange(aiUser) if e != nil { resp = models.BaseResponse{Ret: 408, Msg: "重登录失败,请稍后重试!", ErrMsg: fmt.Sprint(e)} } else { resp = models.BaseResponse{Ret: models.BaseRespReLoginErr, Msg: "用户切换,请刷新页面", ErrMsg: "user exchanged", Data: newLogin} } isOk = false return } session, err := system.GetSysSessionByToken(token) if err != nil { newLogin, e := services.UserLoginChange(aiUser) if e != nil { resp = models.BaseResponse{Ret: 408, Msg: "重登录失败,请稍后重试!", ErrMsg: fmt.Sprint(e)} } else { resp = models.BaseResponse{Ret: models.BaseRespReLoginErr, Msg: "用户切换,请刷新页面", ErrMsg: "user exchanged", Data: newLogin} } isOk = false return } account := utils.MD5(session.UserName) loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id) loginCache, _ := utils.Rc.RedisString(loginKey) if session.UserName != aiUser || !utils.CheckToken(account, token) || time.Now().After(session.ExpiredTime) || (session.IsRemember != 1 && loginCache == ``) { newLogin, e := services.UserLoginChange(aiUser) if e != nil { resp = models.BaseResponse{Ret: 408, Msg: "重登录失败,请稍后重试!", ErrMsg: fmt.Sprint(e)} } else { resp = models.BaseResponse{Ret: models.BaseRespReLoginErr, Msg: "用户切换,请刷新页面", ErrMsg: "user exchanged", Data: newLogin} } isOk = false return } } if token == "" { resp = models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"} isOk = false return } return }