mobile_api_base_controller.go 8.8KB

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