123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740 |
- 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
- // 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",
- }
- type BaseAuthController struct {
- web.Controller
- SysUser *system.Admin
- Session *system.SysSession
- Lang string `description:"当前语言类型,中文:zh;英文:en;默认:zh"`
- }
- //func (c *BaseAuthController) Prepare() {
- // //fmt.Println("enter prepare")
- // method := c.Ctx.Input.Method()
- // uri := c.Ctx.Input.URI()
- // //fmt.Println("Url:", uri)
- // if method != "HEAD" {
- // if method == "POST" || method == "GET" {
- // // 当前语言
- // {
- // lang := c.Ctx.Input.Header("Lang")
- // if lang == "" {
- // lang = utils.ZhLangVersion
- // }
- // c.Lang = lang
- // }
- //
- // 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)
- // }
- // }
- // if authorization == "" {
- // c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
- // c.StopRun()
- // return
- // }
- // //authorizationArr := strings.Split(authorization, "$")
- // //if len(authorizationArr) <= 1 {
- // // c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
- // // c.StopRun()
- // // return
- // //}
- // tokenStr := authorization
- // tokenArr := strings.Split(tokenStr, "=")
- // token := tokenArr[1]
- //
- // //accountStr := authorizationArr[1]
- // //accountArr := strings.Split(accountStr, "=")
- // //account := accountArr[1]
- //
- // 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
- // }
- // //校验token是否合法
- // // JWT校验Token和Account
- // 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 loginInfo != "1" {
- // lastLoginTime := admin.LastLoginTime
- //
- // lastLoginTimeObj, err := time.Parse(utils.FormatDateWallWithLoc, lastLoginTime)
- // fmt.Println(lastLoginTimeObj, err)
- //
- // msg := `该账号于` + lastLoginTimeObj.Format(utils.FormatDateTime) + "在其他网络登录。此客户端已退出登录。"
- // c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
- // c.StopRun()
- // return
- // }
- //
- // // 如果是ETA体验版-更新活跃时长/更新登录时长的接口请求, 则不更新Token时长
- // 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 + "&"
- // }
- // }
- //
- // //fmt.Println(api)
- // //处理uri请求,去除前缀和参数
- // api = strings.TrimRight(api, "&")
- // uri = strings.Replace(uri, "/adminapi", "", 1)
- // uris := strings.Split(uri, "?")
- // uri = uris[0]
- // //fmt.Println("uri:", uri)
- // apis := strings.Split(api, "&")
- // apiMap := make(map[string]bool, 0)
- // for _, s := range apis {
- // apiMap[s] = true
- // }
- //
- // fmt.Println("uri:", uri)
- //
- // //fmt.Println(apiMap)
- // if !apiMap[uri] {
- // c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
- // c.StopRun()
- // return
- // }
- // } else {
- // c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
- // c.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()+"<br/> "+"Params"+requestBody+" <br/>"+"ErrMsg:"+baseRes.ErrMsg+";<br/>Msg:"+baseRes.Msg+";<br/> Body:"+string(body)+"<br/>"+c.SysUser.RealName, utils.EmailSendToUsers)
- body := "URI:" + c.Ctx.Input.URI() + "<br/> " + "Params" + requestBody + " <br/>" + "ErrMsg:" + baseRes.ErrMsg + ";<br/>Msg:" + baseRes.Msg + ";<br/> Body:" + string(body) + "<br/>" + 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)
- }
- }
- }
- //新增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")
- desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
- c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
- // 设置Cookie为HTTPOnly
- c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
- //fmt.Println(c.Ctx.ResponseWriter.Header().Get("Set-Cookie"))
- 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)
- // 如果不是debug分支的话,那么需要加密返回
- if utils.RunMode != "debug" {
- content = utils.DesBase64Encrypt(content, utils.DesKey)
- // 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 ""
- }
- func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
- authorization := ""
- method := c.Ctx.Input.Method()
- uri := c.Ctx.Input.URI()
- //fmt.Println("Url:", 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() {
- //fmt.Println("enter 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()
- //fmt.Println("Url:", 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
- }
- //accountStr := authorizationArr[1]
- //accountArr := strings.Split(accountStr, "=")
- //account := accountArr[1]
- session, err := system.GetSysSessionByToken(token)
- //fmt.Println("session:", session)
- 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
- }
- //校验token是否合法
- // JWT校验Token和Account
- 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 loginInfo != "1" {
- // lastLoginTime := admin.LastLoginTime
- //
- // lastLoginTimeObj, err := time.Parse(utils.FormatDateWallWithLoc, lastLoginTime)
- // fmt.Println(lastLoginTimeObj, err)
- //
- // msg := `该账号于` + lastLoginTimeObj.Format(utils.FormatDateTime) + "在其他网络登录。此客户端已退出登录。"
- // c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
- // c.StopRun()
- // return
- //}
- // 如果是ETA体验版-更新活跃时长/更新登录时长的接口请求, 则不更新Token时长
- 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 + "&"
- }
- }
- //fmt.Println(api)
- //处理uri请求,去除前缀和参数
- api = strings.TrimRight(api, "&")
- uri = strings.Replace(uri, "/adminapi", "", 1)
- uris := strings.Split(uri, "?")
- uri = uris[0]
- //fmt.Println("uri:", uri)
- apis := strings.Split(api, "&")
- apiMap := make(map[string]bool, 0)
- for _, s := range apis {
- apiMap[s] = true
- }
- //fmt.Println("uri:", uri)
- //fmt.Println(apiMap)
- if !apiMap[uri] {
- c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问!", ErrMsg: "无权访问!"}, false, false)
- c.StopRun()
- return
- }
- }
- // checkToken
- // @Description: 校验token
- // @author: Roc
- // @datetime 2024-10-30 11:29:37
- // @param c *BaseAuthController
- // @return isOk bool
- // @return token string
- // @return resp models.BaseResponse
- 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, "?")
- //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 != "" {
- 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)
- //fmt.Println("token:", token)
- if aiUser != "" {
- // Token空了, 以Cookie为准重新登录
- 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
- }
- // todo 将aiUser与session进行关联
- // token不为空, 那么去校验一下token是否过期, 以及和cookieVal是否匹配
- // 找不到session, 也直接切CookieValue中的用户登录
- 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
- }
- // CookieVal不匹配、token验证失败、session以及redis中的token过期,那么以cookieVal的用户去登录并返回4014
- 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
- }
|