mobile_api_base_controller.go 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package mobile_api_controllers
  2. import (
  3. "XT_New/controllers"
  4. "XT_New/enums"
  5. "XT_New/models"
  6. "XT_New/service"
  7. "bytes"
  8. "encoding/json"
  9. "fmt"
  10. "log"
  11. "os"
  12. "path"
  13. "regexp"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. type MobileBaseAPIController struct {
  20. controllers.BaseAPIController
  21. }
  22. func (this *MobileBaseAPIController) Prepare() {
  23. this.BaseAPIController.Prepare()
  24. // beego.Trace("============================================================")
  25. // beego.Trace("session ID: %v", this.Ctx.Input.Cookie("beegosessionID"))
  26. // beego.Trace("session : %v", this.GetSession("info"))
  27. // this.SetSession("info", time.Now().Format("2006/01/02 15:04:05"))
  28. // beego.Trace("============================================================")
  29. }
  30. //
  31. func (this *MobileBaseAPIController) GetMobileAdminUserInfo() *MobileAdminUserInfo {
  32. userInfo := this.GetSession("mobile_admin_user_info")
  33. if userInfo == nil {
  34. return nil
  35. } else {
  36. return userInfo.(*MobileAdminUserInfo)
  37. }
  38. }
  39. type MobileAdminUserInfo struct {
  40. AdminUser *models.AdminUser
  41. Org *models.Org
  42. App *models.OrgApp
  43. AppRole *models.App_Role
  44. Subscibe *models.ServeSubscibe
  45. TemplateInfo *models.GobalTemplate
  46. }
  47. type MobileBaseAPIAuthController struct {
  48. MobileBaseAPIController
  49. }
  50. func (this *MobileBaseAPIAuthController) Prepare() {
  51. token := this.Ctx.GetCookie("token_cookie")
  52. logout_cookie := this.Ctx.GetCookie("logout_cookie")
  53. //if len(token) == 0{
  54. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
  55. // this.StopRun()
  56. //}
  57. this.MobileBaseAPIController.Prepare()
  58. adminUserInfo := this.GetMobileAdminUserInfo()
  59. if len(token) == 0 {
  60. this.DelSession("mobile_admin_user_info")
  61. // fmt.Println(logout_cookie)
  62. if len(logout_cookie) == 1 {
  63. this.Ctx.SetCookie("logout_cookie", "2")
  64. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeLogOut)
  65. this.StopRun()
  66. } else {
  67. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
  68. this.StopRun()
  69. }
  70. } else {
  71. if adminUserInfo == nil {
  72. this.DelSession("mobile_admin_user_info")
  73. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
  74. this.StopRun()
  75. }
  76. }
  77. //if this.Ctx.Request.Method != "GET" {
  78. // err := service.GetOrgSubscibeState(adminUserInfo.Subscibe)
  79. // if err != nil || adminUserInfo.Subscibe.State == 3 {
  80. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotSubscibe)
  81. // this.StopRun()
  82. // }
  83. //}
  84. if adminUserInfo.AppRole != nil {
  85. if adminUserInfo.AppRole.Id > 0 {
  86. app_role, _ := service.FindAppRoleById(adminUserInfo.AppRole.Id)
  87. if app_role != nil {
  88. if app_role.Status != 1 {
  89. this.DelSession("mobile_admin_user_info")
  90. this.Ctx.SetCookie("token_cookie", "")
  91. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeForbidden)
  92. this.StopRun()
  93. }
  94. }
  95. }
  96. }
  97. if this.Ctx.Request.Header.Get("Permission") == "1" {
  98. if adminUserInfo.AdminUser.Id != adminUserInfo.Org.Creator { //超级管理员不受此限制
  99. err_msgs := LoadErrMsgConfig("./err_msg.json").Msgs
  100. isPermission := false
  101. adminUserInfo := this.GetMobileAdminUserInfo()
  102. //该机构下该用户有多少个
  103. redisClient := service.RedisClient()
  104. defer redisClient.Close()
  105. key2 := strconv.FormatInt(adminUserInfo.Org.Id, 10) + "_" + strconv.FormatInt(adminUserInfo.AdminUser.Id, 10) + "_role_ids"
  106. result, _ := redisClient.Get(key2).Result()
  107. var role models.App_Role
  108. var roles []string
  109. if len(result) == 0 {
  110. //该机构下该用户有多少个
  111. role, _ = service.GetUserAllRole(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id)
  112. redisClient.Set(key2, role, time.Second*60*60*18)
  113. if len(role.RoleIds) > 0 { //该用户没有设置角色
  114. roles = strings.Split(role.RoleIds, ",")
  115. }
  116. } else {
  117. json.Unmarshal([]byte(result), &role)
  118. if len(role.RoleIds) > 0 { //该用户没有设置角色
  119. roles = strings.Split(role.RoleIds, ",")
  120. }
  121. }
  122. //redis相关处理逻辑
  123. redis := service.RedisClient()
  124. defer redis.Close()
  125. //redis key值
  126. key := "purviews_" + strconv.FormatInt(adminUserInfo.Org.Id, 10) + strconv.FormatInt(adminUserInfo.AdminUser.Id, 10)
  127. fmt.Println("ket--------------------", key)
  128. redis.Set(key, "", time.Second)
  129. purviews_json_str, _ := redis.Get(key).Result()
  130. //获取该用户下所有角色的权限总集
  131. var userRolePurviews string
  132. var userRolePurviewsArr []string
  133. //fmt.Println("----redis 开始----")
  134. //fmt.Println(purviews_json_str)
  135. //fmt.Println("----redis 结束----")
  136. if len(purviews_json_str) == 0 {
  137. for _, item := range roles {
  138. role_id, _ := strconv.ParseInt(item, 10, 64)
  139. purviews, _ := service.GetRoleFuncPurviewIds(role_id)
  140. if len(userRolePurviews) == 0 {
  141. userRolePurviews = purviews
  142. } else {
  143. userRolePurviews = userRolePurviews + "," + purviews
  144. }
  145. }
  146. //该用户所拥有角色的权限的总集
  147. userRolePurviewsArr = RemoveRepeatedPurviewElement(strings.Split(userRolePurviews, ","))
  148. //缓存数据
  149. purview_json, err := json.Marshal(userRolePurviewsArr)
  150. if err == nil {
  151. redis.Set(key, purview_json, time.Minute*60*60*24)
  152. }
  153. } else {
  154. var dat []string
  155. if err := json.Unmarshal([]byte(purviews_json_str), &dat); err == nil {
  156. } else {
  157. }
  158. userRolePurviewsArr = dat
  159. }
  160. // fmt.Println(userRolePurviewsArr)
  161. //系统所记录的权限列表
  162. allPermission, _ := service.GetAllFunctionPurview()
  163. for _, item := range allPermission {
  164. //判断当前路由是否在权限路由列表里面
  165. if strings.Split(item.Urlfor, ",")[0] == strings.Split(this.Ctx.Request.RequestURI, "?")[0]+"?"+"mode="+this.GetString("mode") {
  166. //获取该角色的所有权限
  167. for _, items := range userRolePurviewsArr {
  168. id, _ := strconv.ParseInt(items, 10, 64)
  169. if id == item.ID {
  170. isPermission = true
  171. }
  172. }
  173. if !isPermission {
  174. //msg, _ := service.FindErrorMsgByStr(strings.Split(this.Ctx.Request.RequestURI, "?")[0] + "?" + "mode=" + this.GetString("mode"))
  175. var msg string
  176. for _, item := range err_msgs {
  177. if strings.Index(item.Url, strings.Split(this.Ctx.Request.RequestURI, "?")[0]+"?"+"mode="+this.GetString("mode")) != -1 {
  178. msg = item.ErrMsg
  179. }
  180. }
  181. json := make(map[string]interface{})
  182. json["msg"] = msg
  183. json["code"] = 0
  184. json["state"] = 0
  185. this.Data["json"] = json
  186. this.ServeJSON()
  187. this.StopRun()
  188. }
  189. }
  190. }
  191. }
  192. }
  193. }
  194. func RemoveRepeatedPurviewElement(arr []string) (newArr []string) {
  195. newArr = make([]string, 0)
  196. for i := 0; i < len(arr); i++ {
  197. repeat := false
  198. for j := i + 1; j < len(arr); j++ {
  199. if arr[i] == arr[j] {
  200. repeat = true
  201. break
  202. }
  203. }
  204. if !repeat {
  205. newArr = append(newArr, arr[i])
  206. }
  207. }
  208. return
  209. }
  210. type AdminUserInfo struct {
  211. AdminUser *models.AdminUser `json:"user"`
  212. CurrentOrgId int64 `json:"current_org_id"`
  213. CurrentAppId int64 `json:"current_app_id"`
  214. OrgIds []int64 `json:"org_ids"`
  215. Orgs map[int64]*models.Org `json:"orgs"`
  216. OrgAppIds map[int64][]int64 `json:"org_app_ids"`
  217. OrgApps map[int64](map[int64]*models.OrgApp) `json:"org_apps"`
  218. App2OrgIds map[int64]int64 `json:"app_to_org_ids"`
  219. AppRoles map[int64]*models.App_Role `json:"app_roles"`
  220. AppPurviews map[int64][]*models.Purview `json:"app_purviews"`
  221. AppUrlfors map[int64][]string `json:"app_urlfors"`
  222. Subscibes map[int64]*models.ServeSubscibe `json:"org_subscibes"`
  223. }
  224. type ErrMsgConfig struct {
  225. Msgs []*models.ErrMsg "json:msg"
  226. }
  227. func LoadErrMsgConfig(dataFile string) *ErrMsgConfig {
  228. var config ErrMsgConfig
  229. _, filename, _, _ := runtime.Caller(1)
  230. datapath := path.Join(path.Dir(filename), dataFile)
  231. config_file, err := os.Open(datapath)
  232. if err != nil {
  233. emit("Failed to open config file '%s': %s\n", datapath, err)
  234. return &config
  235. }
  236. fi, _ := config_file.Stat()
  237. buffer := make([]byte, fi.Size())
  238. _, err = config_file.Read(buffer)
  239. buffer, err = StripComments(buffer) //去掉注释
  240. if err != nil {
  241. emit("Failed to strip comments from json: %s\n", err)
  242. return &config
  243. }
  244. buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
  245. err = json.Unmarshal(buffer, &config) //解析json格式数据
  246. if err != nil {
  247. emit("Failed unmarshalling json: %s\n", err)
  248. return &config
  249. }
  250. return &config
  251. }
  252. func emit(msgfmt string, args ...interface{}) {
  253. log.Printf(msgfmt, args...)
  254. }
  255. func StripComments(data []byte) ([]byte, error) {
  256. data = bytes.Replace(data, []byte("\r"), []byte(""), 0) // Windows
  257. lines := bytes.Split(data, []byte("\n")) //split to muli lines
  258. filtered := make([][]byte, 0)
  259. for _, line := range lines {
  260. match, err := regexp.Match(`^\s*#`, line)
  261. if err != nil {
  262. return nil, err
  263. }
  264. if !match {
  265. filtered = append(filtered, line)
  266. }
  267. }
  268. return bytes.Join(filtered, []byte("\n")), nil
  269. }