mobile_api_base_controller.go 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. 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. }