base_api_controller.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. package controllers
  2. import (
  3. "XT_New/enums"
  4. "XT_New/models"
  5. "XT_New/service"
  6. "encoding/json"
  7. "os"
  8. "path"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. type BaseAPIController struct {
  15. BaseController
  16. }
  17. // func (this *BaseAPIController) Prepare() {
  18. // this.BaseController.Prepare()
  19. // beego.Trace("============================================================")
  20. // beego.Trace("session ID: %v", this.Ctx.Input.Cookie("beegosessionID"))
  21. // beego.Trace("session : %v", this.GetSession("info"))
  22. // this.SetSession("info", time.Now().Format("2006/01/02 15:04:05"))
  23. // beego.Trace("============================================================")
  24. // }
  25. // 输出数据格式化
  26. /*
  27. success json:
  28. {
  29. "state": 1,
  30. "code": 0,
  31. "data": json,
  32. }
  33. fail json:
  34. {
  35. "state": 0,
  36. "code": int,
  37. "msg": string,
  38. }
  39. */
  40. func (this *BaseAPIController) ServeSuccessJSON(data map[string]interface{}) {
  41. this.Data["json"] = enums.MakeSuccessResponseJSON(data)
  42. this.ServeJSON()
  43. }
  44. func (this *BaseAPIController) ServeFailJSONWithSGJErrorCode(code int) {
  45. this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(code)
  46. this.ServeJSON()
  47. }
  48. func (this *BaseAPIController) ServeFailJSONWithSGJError(err *enums.SGJError) {
  49. this.Data["json"] = enums.MakeFailResponseJSONWithSGJError(err)
  50. this.ServeJSON()
  51. }
  52. func (this *BaseAPIController) ServeFailJsonSend(code int, msg string) {
  53. this.Data["json"] = enums.MakeFailResponseJSON(msg, code)
  54. this.ServeJSON()
  55. }
  56. func (this *BaseAPIController) ServeDynamicFailJsonSend(msg string) {
  57. this.Data["json"] = enums.MakeDynamicFailResponseJSON(msg)
  58. this.ServeJSON()
  59. }
  60. type BaseAuthAPIController struct {
  61. BaseAPIController
  62. }
  63. func (this *BaseAuthAPIController) Prepare() {
  64. this.BaseAPIController.Prepare()
  65. if this.GetAdminUserInfo() == nil {
  66. var userAdmin models.AdminUser
  67. userAdmin.Id = 1448
  68. userAdmin.Mobile = "13318599895"
  69. userAdmin.Id = 597
  70. userAdmin.Mobile = "19874122664"
  71. userAdmin.IsSuperAdmin = false
  72. userAdmin.Status = 1
  73. userAdmin.CreateTime = 1530786071
  74. userAdmin.ModifyTime = 1530786071
  75. var subscibe models.ServeSubscibe
  76. subscibe.ID = 1
  77. subscibe.OrgId = 10215
  78. subscibe.PeriodStart = 1538035409
  79. subscibe.PeriodEnd = 1569571409
  80. subscibe.State = 1
  81. subscibe.Status = 1
  82. subscibe.CreatedTime = 1538035409
  83. subscibe.UpdatedTime = 1538035409
  84. subscibes := make(map[int64]*models.ServeSubscibe, 0)
  85. subscibes[4] = &subscibe
  86. var adminUserInfo service.AdminUserInfo
  87. adminUserInfo.CurrentOrgId = 10215
  88. adminUserInfo.CurrentAppId = 4
  89. adminUserInfo.AdminUser = &userAdmin
  90. adminUserInfo.Subscibes = subscibes
  91. this.SetSession("admin_user_info", &adminUserInfo)
  92. //this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
  93. //this.StopRun()
  94. }
  95. adminUserInfo := this.GetAdminUserInfo()
  96. if this.Ctx.Request.Header.Get("Permission") == "2" {
  97. err_msgs := LoadErrMsgConfig("./err_msg.json").Msgs
  98. org, _ := service.GetOrgById(adminUserInfo.CurrentOrgId)
  99. if adminUserInfo.AdminUser.Id != org.Creator { //超级管理员不受此限制
  100. isPermission := false
  101. adminUserInfo := this.GetAdminUserInfo()
  102. redisClient := service.RedisClient()
  103. defer redisClient.Close()
  104. key := strconv.FormatInt(adminUserInfo.CurrentOrgId, 64) + "_" + strconv.FormatInt(adminUserInfo.AdminUser.Id, 64) + "_role_ids"
  105. result, _ := redisClient.Get(key).Result()
  106. var role models.App_Role
  107. var roles []string
  108. if len(result) == 0 {
  109. //该机构下该用户有多少个
  110. role, _ = service.GetUserAllRole(adminUserInfo.CurrentOrgId, adminUserInfo.AdminUser.Id)
  111. redisClient.Set(key, 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. //key := strconv.FormatInt(role_id, 64) + "_" + strconv.FormatInt(adminUserInfo.AdminUser.Id, 64) + "_role_ids"
  122. //result, _ := redisClient.Get(key).Result()
  123. //获取该用户下所有角色的权限总集
  124. var userRolePurviews string
  125. var userRolePurviewsArr []string
  126. for _, item := range roles {
  127. role_id, _ := strconv.ParseInt(item, 10, 64)
  128. purviews, _ := service.GetRoleFuncPurviewIds(role_id)
  129. if len(userRolePurviews) == 0 {
  130. userRolePurviews = purviews
  131. } else {
  132. userRolePurviews = userRolePurviews + "," + purviews
  133. }
  134. }
  135. //该用户所拥有角色的权限的总集
  136. userRolePurviewsArr = RemoveRepeatedPurviewElement2(strings.Split(userRolePurviews, ","))
  137. //系统所记录的权限列表
  138. allPermission, _ := service.GetAllFunctionPurview()
  139. for _, item := range allPermission {
  140. // fmt.Println(len(strings.Split(item.Urlfor, ",")))
  141. // fmt.Println(strings.Split(item.Urlfor, ","))
  142. //fmt.Println(strings.Split(this.Ctx.Request.RequestURI, "?")[0] + "?" + "mode=" + this.GetString("mode"))
  143. //判断当前路由是否在权限路由列表里面
  144. if strings.Split(item.Urlfor, ",")[1] == strings.Split(this.Ctx.Request.RequestURI, "?")[0]+"?"+"mode="+this.GetString("mode") {
  145. //获取该角色的所有权限
  146. for _, items := range userRolePurviewsArr {
  147. id, _ := strconv.ParseInt(items, 10, 64)
  148. if id == item.ID {
  149. isPermission = true
  150. }
  151. }
  152. if !isPermission {
  153. var msg string
  154. for _, item := range err_msgs {
  155. if strings.Index(item.Url, strings.Split(this.Ctx.Request.RequestURI, "?")[0]+"?"+"mode="+this.GetString("mode")) != -1 {
  156. msg = item.ErrMsg
  157. }
  158. }
  159. //msg, _ := service.FindErrorMsgByStr(strings.Split(this.Ctx.Request.RequestURI, "?")[0] + "?" + "mode=" + this.GetString("mode"))
  160. json := make(map[string]interface{})
  161. json["msg"] = msg
  162. json["code"] = 0
  163. json["state"] = 0
  164. this.Data["json"] = json
  165. this.ServeJSON()
  166. this.StopRun()
  167. }
  168. }
  169. }
  170. }
  171. }
  172. if this.Ctx.Request.Header.Get("Permission") == "3" {
  173. err_msgs := LoadErrMsgConfig("./err_msg.json").Msgs
  174. org, _ := service.GetOrgById(adminUserInfo.CurrentOrgId)
  175. if adminUserInfo.AdminUser.Id != org.Creator { //超级管理员不受此限制
  176. isPermission := false
  177. adminUserInfo := this.GetAdminUserInfo()
  178. //该机构下该用户有多少个
  179. redisClient := service.RedisClient()
  180. defer redisClient.Close()
  181. key := strconv.FormatInt(adminUserInfo.CurrentOrgId, 64) + "_" + strconv.FormatInt(adminUserInfo.AdminUser.Id, 64) + "_role_ids"
  182. result, _ := redisClient.Get(key).Result()
  183. var role models.App_Role
  184. var roles []string
  185. if len(result) == 0 {
  186. //该机构下该用户有多少个
  187. role, _ = service.GetUserAllRole(adminUserInfo.CurrentOrgId, adminUserInfo.AdminUser.Id)
  188. redisClient.Set(key, role, time.Second*60*60*18)
  189. if len(role.RoleIds) > 0 { //该用户没有设置角色
  190. roles = strings.Split(role.RoleIds, ",")
  191. }
  192. } else {
  193. json.Unmarshal([]byte(result), &role)
  194. if len(role.RoleIds) > 0 { //该用户没有设置角色
  195. roles = strings.Split(role.RoleIds, ",")
  196. }
  197. }
  198. //获取该用户下所有角色的权限总集
  199. var userRolePurviews string
  200. var userRolePurviewsArr []string
  201. for _, item := range roles {
  202. role_id, _ := strconv.ParseInt(item, 10, 64)
  203. purviews, _ := service.GetRoleFuncPurviewIds(role_id)
  204. if len(userRolePurviews) == 0 {
  205. userRolePurviews = purviews
  206. } else {
  207. userRolePurviews = userRolePurviews + "," + purviews
  208. }
  209. }
  210. //该用户所拥有角色的权限的总集
  211. userRolePurviewsArr = RemoveRepeatedPurviewElement2(strings.Split(userRolePurviews, ","))
  212. //系统所记录的权限列表
  213. allPermission, _ := service.GetAllFunctionPurview()
  214. for _, item := range allPermission {
  215. // fmt.Println(strings.Split(item.Urlfor, ",")[2])
  216. // fmt.Println(strings.Split(this.Ctx.Request.RequestURI, "?")[0] + "?" + "mode=" + this.GetString("mode"))
  217. //判断当前路由是否在权限路由列表里面
  218. if strings.Split(item.Urlfor, ",")[2] == strings.Split(this.Ctx.Request.RequestURI, "?")[0]+"?"+"mode="+this.GetString("mode") {
  219. //获取该角色的所有权限
  220. for _, items := range userRolePurviewsArr {
  221. id, _ := strconv.ParseInt(items, 10, 64)
  222. if id == item.ID {
  223. isPermission = true
  224. }
  225. }
  226. if !isPermission {
  227. var msg string
  228. for _, item := range err_msgs {
  229. if strings.Index(item.Url, strings.Split(this.Ctx.Request.RequestURI, "?")[0]+"?"+"mode="+this.GetString("mode")) != -1 {
  230. msg = item.ErrMsg
  231. }
  232. }
  233. //msg, _ := service.FindErrorMsgByStr(strings.Split(this.Ctx.Request.RequestURI, "?")[0] + "?" + "mode=" + this.GetString("mode"))
  234. json := make(map[string]interface{})
  235. json["msg"] = msg
  236. json["code"] = 0
  237. json["state"] = 0
  238. this.Data["json"] = json
  239. this.ServeJSON()
  240. this.StopRun()
  241. }
  242. }
  243. }
  244. }
  245. }
  246. //if this.Ctx.Request.Method != "GET" {
  247. // adminUserInfo := this.GetAdminUserInfo()
  248. //
  249. // err := service.GetOrgSubscibeState(adminUserInfo.Subscibes[adminUserInfo.CurrentOrgId])
  250. // if err != nil || adminUserInfo.Subscibes[adminUserInfo.CurrentOrgId].State == 3 {
  251. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotSubscibe)
  252. // this.StopRun()
  253. // }
  254. //}
  255. //if this.Ctx.Request.Header.Get("Permission") == "1" {
  256. // isPermission := false
  257. //
  258. // //adminUserInfo := this.GetAdminUserInfo()
  259. //
  260. // //service.GetUserAllRole(adminUserInfo.CurrentOrgId)
  261. //
  262. //
  263. //
  264. //
  265. // roles := []int64{1,2} //模拟该用户有多少角色
  266. // var targetRole models.RolePurview
  267. // var userRolePurview []string
  268. //
  269. // //用户角色1对应的权限
  270. // role1 := models.RolePurview{PurviewIds:"11,12,13"}
  271. //
  272. // //用户角色2对应的权限
  273. // role2 := models.RolePurview{PurviewIds:"11,15,16"}
  274. //
  275. //
  276. // //模拟角色2
  277. // //判断该用户有多少个角色,合并最大角色权限
  278. // if len(roles) == 1{ //单个
  279. // targetRole = role1
  280. // userRolePurview = strings.Split(targetRole.PurviewIds, ",")
  281. //
  282. // }else{ //多个
  283. // targetRole = role1
  284. // targetRole.PurviewIds = targetRole.PurviewIds + "," + role2.PurviewIds
  285. // userRolePurview = strings.Split(targetRole.PurviewIds, ",")
  286. // }
  287. //
  288. // userRolePurview = RemoveRepeatedElement2(userRolePurview)
  289. //
  290. // fmt.Println(userRolePurview)
  291. // //所有权限列表
  292. // allPermission := []models.Purview{{Id:10,Urlfor:"/m/api/dialysis/dialysisPrescription-/api/dialysis/prescription"},
  293. // {Id:11,Urlfor:"/m/api/dialysis/dialysisPrescription1-/api/dialysis/prescription1"},
  294. // {Id:12,Urlfor:"/m/api/dialysis/dialysisPrescription2-/api/dialysis/prescription2"},
  295. // {Id:13,Urlfor:"/m/api/dialysis/dialysisPrescription3-/api/dialysis/prescription3"},
  296. // {Id:14,Urlfor:"/m/api/dialysis/dialysisPrescription4-/api/dialysis/prescription4"},
  297. // {Id:15,Urlfor:"/m/api/dialysis/dialysisPrescription5-/api/dialysis/prescription5"},
  298. // {Id:16,Urlfor:"/m/api/dialysis/dialysisPrescription6-/api/dialysis/prescription6"}}
  299. // for _, item := range allPermission {
  300. // //判断当前路由是否在权限路由列表里面
  301. // if strings.Split(item.Urlfor, "-")[1] == strings.Split(this.Ctx.Request.RequestURI , "?")[0]{
  302. // fmt.Println(strings.Split(this.Ctx.Request.RequestURI , "?")[0])
  303. //
  304. // //获取该角色的所有权限
  305. // for _, items := range userRolePurview{
  306. // id, _ := strconv.ParseInt(items, 10, 64)
  307. // if id == item.Id{
  308. // isPermission = true
  309. // }
  310. // }
  311. // if !isPermission{
  312. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePreExist)
  313. // this.StopRun()
  314. // }
  315. // }
  316. //
  317. // }
  318. //}
  319. }
  320. type BaseServeAPIController struct {
  321. BaseAPIController
  322. }
  323. func (this *BaseServeAPIController) Prepare() {
  324. this.BaseAPIController.Prepare()
  325. if this.GetAdminUserInfo() == nil {
  326. var userAdmin models.AdminUser
  327. userAdmin.Id = 1448
  328. userAdmin.Mobile = "13318599895"
  329. userAdmin.Id = 597
  330. userAdmin.Mobile = "19874122664"
  331. userAdmin.IsSuperAdmin = false
  332. userAdmin.Status = 1
  333. userAdmin.CreateTime = 1530786071
  334. userAdmin.ModifyTime = 1530786071
  335. var subscibe models.ServeSubscibe
  336. subscibe.ID = 1
  337. subscibe.OrgId = 10215
  338. subscibe.PeriodStart = 1538035409
  339. subscibe.PeriodEnd = 1569571409
  340. subscibe.State = 1
  341. subscibe.Status = 1
  342. subscibe.CreatedTime = 1538035409
  343. subscibe.UpdatedTime = 1538035409
  344. subscibes := make(map[int64]*models.ServeSubscibe, 0)
  345. subscibes[4] = &subscibe
  346. var adminUserInfo service.AdminUserInfo
  347. adminUserInfo.CurrentOrgId = 10215
  348. adminUserInfo.CurrentAppId = 4
  349. adminUserInfo.AdminUser = &userAdmin
  350. adminUserInfo.Subscibes = subscibes
  351. this.SetSession("admin_user_info", &adminUserInfo)
  352. //this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNotLogin)
  353. //this.StopRun()
  354. }
  355. //if adminUserInfo.AppRole != nil {
  356. // if adminUserInfo.AppRole.Id > 0 {
  357. // app_role, _ := service.FindAppRoleById(adminUserInfo.AppRole.Id)
  358. // if app_role != nil {
  359. // if app_role.Status != 1 {
  360. // this.DelSession("mobile_admin_user_info")
  361. // this.Ctx.SetCookie("token_cookie", "")
  362. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeForbidden)
  363. // this.StopRun()
  364. // }
  365. // }
  366. // }
  367. //
  368. //}
  369. //fmt.Println("222222222")
  370. }
  371. func RemoveRepeatedPurviewElement2(arr []string) (newArr []string) {
  372. newArr = make([]string, 0)
  373. for i := 0; i < len(arr); i++ {
  374. repeat := false
  375. for j := i + 1; j < len(arr); j++ {
  376. if arr[i] == arr[j] {
  377. repeat = true
  378. break
  379. }
  380. }
  381. if !repeat {
  382. newArr = append(newArr, arr[i])
  383. }
  384. }
  385. return
  386. }
  387. type ErrMsgConfig struct {
  388. Msgs []*models.ErrMsg "json:msg"
  389. }
  390. func LoadErrMsgConfig(dataFile string) *ErrMsgConfig {
  391. var config ErrMsgConfig
  392. _, filename, _, _ := runtime.Caller(1)
  393. datapath := path.Join(path.Dir(filename), dataFile)
  394. config_file, err := os.Open(datapath)
  395. if err != nil {
  396. emit("Failed to open config file '%s': %s\n", datapath, err)
  397. return &config
  398. }
  399. fi, _ := config_file.Stat()
  400. buffer := make([]byte, fi.Size())
  401. _, err = config_file.Read(buffer)
  402. buffer, err = StripComments(buffer) //去掉注释
  403. if err != nil {
  404. emit("Failed to strip comments from json: %s\n", err)
  405. return &config
  406. }
  407. buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
  408. err = json.Unmarshal(buffer, &config) //解析json格式数据
  409. if err != nil {
  410. emit("Failed unmarshalling json: %s\n", err)
  411. return &config
  412. }
  413. return &config
  414. }